【问题标题】:Comments are getting deleted after updating .properties file [duplicate]更新.properties文件后评论被删除[重复]
【发布时间】:2015-05-26 22:00:46
【问题描述】:

我有一个 .properties 文件,其中包含多个 cmets,当我尝试更新 cmets 以外的文件内容时,即使我的 cmets 正在消失,如何保留我的 cmets?

这里是 config.properties 文件:

#name of user
name=user1
#id of user
id=id1

以及更新属性文件的代码,我用过

public class SetLog {
    public static void setPath()
    {
        File file = new File("./config.properties");
           Properties prop = new Properties();
           FileInputStream objInput = null;
           try {
            objInput = new FileInputStream(file);
            prop.load(objInput);
            objInput.close();

        FileOutputStream out = new FileOutputStream("./config.properties");
//update the content
               prop.setProperty("name", "user2");
              prop.store(out, null);
               out.close();
            } catch (Exception e) {}              
    }

}

我运行上面的代码后,属性文件内容变为:

name=user2
id=id1

但我想要这种格式:

 #name of user
 name=user2
 #id of user
 id=id1

如何留住我的cmets,请帮忙!

【问题讨论】:

  • 可能是 XML 格式? storeToXML 和 loadFromXML?这也有助于以 UTF-8 的形式使用 Unicode。

标签: java file


【解决方案1】:

这已在类似问题中得到解答:Adding comments in a Property File。基本上归结为使用 Apache Commons 扩展来读取和写入属性文件。

【讨论】:

  • 如果已经回答,那么最好将此问题标记为重复。
  • 我已经这样标记了,汤姆
【解决方案2】:

尝试读取文件中的字符并忽略那些以 # 开头的行。

看到这个link

【讨论】:

  • 我认为 OP 希望维护 cmets。没有保存在属性中,因此在存储属性时会消失。
  • 是的,一旦读取了 cmets,就可以在使用新属性更新文件时将它们写回到文件中。事实上,更好的是,可以使用更新的评论历史记录和/或日期时间戳来更新 cmets。
  • @E2241,我有点需要你提供的链接中提到的问题的解决方案,但我无法理解代码,我们不能用简单的方式实现它吗?在更新键值时保持我们的 cmets 不变?
  • 恐怕没有其他内置的属性类,至少我知道。您必须从文件中读取以 # 开头的行,然后将它们写回 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 2011-10-11
相关资源
最近更新 更多