[英]How to properly save a properties file with special characters
I have a property file like this: 我有一个像这样的属性文件:
[flags]
prop1=value
prop2=value
[patterns]
prop3=#.00
prop4=###,##0.00
[other]
prop5=value
When I process the file, not only the pound signs are escaped (#), but all my properties are out of order. 当我处理文件时,不仅转义了井号(#),而且我的所有属性都乱了。
my code is something like this: 我的代码是这样的:
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
}
I am using props.store()
because I do not know of another way to save the properties file after props.setProperty()
is called. 我使用
props.store()
因为我不知道的另一种方式来保存后的属性文件props.setProperty()
被调用。
All the credit goes to Jon Skeet for pointing out that Java Properties are not meant to be used this way, and that what I needed was a Windows-style .ini file. 所有这些功劳归功于Jon Skeet,他指出Java属性并不是要以这种方式使用,而我需要的是Windows风格的.ini文件。 Because of this suggestion, I remember I used
ini4j
many years ago and that is what I needed to use in this case. 由于这个建议,我记得很多年前我使用过
ini4j
,这就是我在这种情况下需要使用的。
The solution is quite simple: 解决方案非常简单:
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!
}
When using ini4j
to save, my properties are preserved in sections, and the order of properties is preserved, and special characters (like #) are not escaped; 当使用
ini4j
进行保存时,我的属性将保留在各节中,并且属性的顺序将保留,并且特殊字符(如#)不会转义。 which addresses ALL of the issues. 解决了所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.