【发布时间】:2012-01-08 15:27:37
【问题描述】:
我最近发现了 java.util.Properties,它允许我在配置中写入和读取,而无需为它编写自己的函数。
我很兴奋,因为它很容易使用,但后来我在存储修改后的配置文件时发现了一个缺陷。
这是我的代码,现在很简单:
FileWriter writer = null;
Properties configFile = new Properties();
configFile.load(ReadFileTest.class.getClassLoader().getResourceAsStream("config.txt"));
String screenwidth = configFile.getProperty("screenwidth");
String screenheight = configFile.getProperty("screenheight");
System.out.println(screenwidth);
System.out.println(screenheight);
configFile.setProperty("screenwidth", "1024");
configFile.setProperty("screenheight", "600");
try {
writer = new FileWriter("config.txt" );
configFile.store(writer, null);
} catch (IOException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
我注意到的问题是我尝试编辑的配置文件是这样存储的:
foo: bar
bar: foo
foobar: barfoo
但是properties.store(writer, null)之后的输出是这样的:
foo=bar
bar=foo
foobar=barfoo
我编辑的配置文件不是针对我的程序,而是针对其他应用程序,该应用程序需要配置文件为上述格式,: 作为分隔符,否则会将配置重置为默认值。
有人知道如何轻松更改吗?
我现在搜索了前 5 个 Google 页面,但没有人遇到类似问题。
我还检查了 Javadoc,发现没有任何函数可以让我在不为自己编写类的情况下更改它。
我现在想使用Properties,因为它在那里并且很容易使用。
保存文件后,我还想到将所有= 替换为:,但也许有人有更好的建议?
【问题讨论】:
标签: java properties divider colon