读取Java属性文件而不转义值

pde*_*eva 19 java properties configuration-files

我的应用程序需要使用.properties文件进行配置.在属性文件中,允许用户指定路径.

问题

属性文件需要转义值,例如

dir = c:\\mydir
Run Code Online (Sandbox Code Playgroud)

需要

我需要一些方法来接受不转义值的属性文件,以便用户可以指定:

dir = c:\mydir
Run Code Online (Sandbox Code Playgroud)

Ian*_*gan 19

为什么不简单地扩展属性类以包含双正斜杠的剥离.这个的一个很好的特点是,通过你的程序的其余部分,你仍然可以使用原始Properties类.

public class PropertiesEx extends Properties {
    public void load(FileInputStream fis) throws IOException {
        Scanner in = new Scanner(fis);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        while(in.hasNext()) {
            out.write(in.nextLine().replace("\\","\\\\").getBytes());
            out.write("\n".getBytes());
        }

        InputStream is = new ByteArrayInputStream(out.toByteArray());
        super.load(is);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用新类很简单:

PropertiesEx p = new PropertiesEx();
p.load(new FileInputStream("C:\\temp\\demo.properties"));
p.list(System.out);
Run Code Online (Sandbox Code Playgroud)

剥离代码也可以改进,但一般原则就在那里.


Mic*_*rdt 6

两种选择:

  • 改为使用XML属性格式
  • 编写自己的解析器以获得修改后的.properties格式,而无需转义


Gre*_*ekz 6

您可以在加载属性之前"预处理"文件,例如:

public InputStream preprocessPropertiesFile(String myFile) throws IOException{
    Scanner in = new Scanner(new FileReader(myFile));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while(in.hasNext())
        out.write(in.nextLine().replace("\\","\\\\").getBytes());
    return new ByteArrayInputStream(out.toByteArray());
}
Run Code Online (Sandbox Code Playgroud)

你的代码看起来就像这样

Properties properties = new Properties();
properties.load(preprocessPropertiesFile("path/myfile.properties"));
Run Code Online (Sandbox Code Playgroud)

这样做,您的.properties文件看起来就像您需要的那样,但您可以使用属性值.

*我知道应该有更好的方法来操作文件,但我希望这会有所帮助.