【问题标题】:How to properly save a properties file with special characters如何正确保存带有特殊字符的属性文件
【发布时间】:2017-04-05 22:09:53
【问题描述】:

我有一个这样的属性文件:

[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() 之后保存属性文件的另一种方法。

【问题讨论】:

  • 听起来您试图错误地使用属性文件。他们不是意味着被订购的,是的,事情会在需要的时候被逃脱。听起来你真的想要一个像 Windows“ini”文件这样的东西......
  • @JonSkeet,谢谢!就是这样。几年前,我使用 ini4j 来做到这一点。我会仔细看看的。再次感谢!

标签: java properties-file


【解决方案1】:

Jon Skeet 指出 Java 属性不应该以这种方式使用,而我需要的是一个 Windows 样式的 .ini 文件,这一切都归功于 Jon Skeet。由于这个建议,我记得很多年前我使用过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保存时,我的属性是分段保存的,属性顺序是保留的,特殊字符(如#)不转义;它解决了所有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多