【问题标题】:Operations with properties file causing issues in Java在 Java 中导致问题的属性文件操作
【发布时间】:2015-12-15 06:31:08
【问题描述】:

我想将新条目附加到已经存在的属性文件中,我使用了下面的代码,我在属性文件中收到的内容是这样的

 #Path to test directory
 #Tue Dec 15 11:36:24 IST 2015
 TestPath=C\:/temp/TestDir
  1. 我从 oracle 文档了解到 this(C\:/temp.....) 是有效的情况。有什么办法可以摆脱这个和时间日期的评论,因为这看起来不太好?

  2. 上述操作需要经常进行,每次运行代码时都会添加相同的更新条目,我可以在属性文件中看到多个条目,我只想拥有一个。

    李>

我读到该文件不应该以附加模式打开以在删除操作后获得正确的输出,但如果不是,那么如何将新条目附加到属性文件。

        Properties properties = new Properties();
        properties.setProperty("TestPath", "C:/temp/TestDir");
        File file = new File("D:\\test.properties");
        FileOutputStream fileOut = new FileOutputStream(file,true);
        properties.store(fileOut, "Path to test directory");
        System.out.println(properties.getProperty("TestPath"));  // prints correct one.

        properties.remove("TestPath");
        properties.store(fileOut,null);
        fileOut.close();

【问题讨论】:

  • “有什么办法可以摆脱这个”什么?您想要替换内容或追加内容,但您不能同时使用一个输出流。我建议阅读属性 (Properties.load),对 Properties 对象进行更改,然后存储(不要追加!)。

标签: java properties-file


【解决方案1】:

如果你需要这个,你必须重写 java.util.Properties 文件的方法 store0。默认情况下,它会将时间戳添加为注释。

【讨论】:

  • 感谢您的建议,这是我第一个问题的一部分。
  • 如果您觉得有用,请点赞。很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2012-10-19
相关资源
最近更新 更多