如何正确保存带有特殊字符的属性文件

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保存时,我的属性是分段保留的,属性顺序保留,特殊字符(如#)不转义;它解决了所有问题。