[英]How to properly save a properties file with special characters
我有一个像这样的属性文件:
[flags]
prop1=value
prop2=value
[patterns]
prop3=#.00
prop4=###,##0.00
[other]
prop5=value
当我处理文件时,不仅转义了井号(#),而且我的所有属性都乱了。
我的代码是这样的:
Properties props = new Properties();
FileInputStream in = null;
try
{
in = new FileInputStream(PROP_FILE);
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
props.load(reader);
}
catch (IOException e)
{
// log exception
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
// log exception
}
}
}
props.setProperty("prop5", "otherValue");
try
{
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(INI_FILE), StandardCharsets.UTF_8);
props.store(w, null);
}
catch (IOException e)
{
// log exception
}
我使用props.store()
因为我不知道的另一种方式来保存后的属性文件props.setProperty()
被调用。
所有这些功劳归功于Jon Skeet,他指出Java属性并不是要以这种方式使用,而我需要的是Windows风格的.ini文件。 由于这个建议,我记得很多年前我使用过ini4j
,这就是我在这种情况下需要使用的。
解决方案非常简单:
try
{
Wini ini = new Wini(new File(PROP_FILE));
ini.put("others", "prop5", value); // "others" is the section, "prop5" the key, and "value" is self-explanatory.
ini.store(); // INI file is saved
}
catch (IOException e)
{
// log problem... do whatever!
}
当使用ini4j
进行保存时,我的属性将保留在各节中,并且属性的顺序将保留,并且特殊字符(如#)不会转义。 解决了所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.