【问题标题】:The .properties file is getting overridden. How to overcome from that?.properties 文件被覆盖。如何克服呢?
【发布时间】:2019-07-23 06:52:05
【问题描述】:

java 中的 config.properties 文件在每次执行后都会被覆盖。我想要的是,以前的数据也应该与新更新的数据一起保存。

下面是我用来将值存储到 config.properties 文件的代码。而且我的 config.properties 文件已经包含一些数据。

try (OutputStream output = new FileOutputStream("path\\to\\config.properties")) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("IFCode", "34253");

            // save properties to project root folder
            prop.store(output, null);

            System.out.println(prop);

        } catch (IOException io) {
            io.printStackTrace();
        }

这是我的 config.properties 文件数据,它已经存在于那里:-

#Tue Jul 23 02:38:34 EDT 2019
File=987
Read=098

现在,当我运行上面的代码时,这些已经可用的数据被省略了,新的数据被写成这样:-

#Tue Jul 23 02:38:34 EDT 2019
IFCode=34253

我想要的基本上是:-

#Tue Jul 23 02:38:34 EDT 2019
File=987
Read=098
IFCode=34253

如何使用 java 解决这个问题?

【问题讨论】:

  • 读取属性,添加属性,然后写入属性。 docs.oracle.com/javase/8/docs/api/java/util/…
  • 文件是否以写入模式而不是追加模式打开?你可以试试看。
  • 当数据存储在那里时,我没有打开文件。唯一的问题是,以前的数据正在丢失。需要解决这个问题。我也使用过 config.save() 。但没有运气。

标签: java properties config


【解决方案1】:

尝试为您的 FileOutputStream 添加布尔附加参数:

OutputStream output = new FileOutputStream("path\\to\\config.properties", true)

FileOutputStream(文件文件,布尔附加) 创建一个文件输出流以写入由指定 File 对象表示的文件。检查参考: https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

【讨论】:

  • 这可行,但如果我想覆盖其 Key 已存在于 config.properties 文件中的值,该怎么办。像这样:- #Tue Jul 23 02:38:34 EDT 2019 File=987 Read=098 IFCode=34253 并且下次运行它然后 IFCode 再次生成如下:- #Tue Jul 23 02:38:34 EDT 2019 文件=987 读取=098 IFCode=34253 IFCode=9868
  • 在这种情况下,您需要 1. 打开文件,2. 从属性文件中读取属性,3. 检查属性是否存在,如果存在,则更改该键的值,否则追加。
【解决方案2】:

解决办法如下:

  try (OutputStream output = new FileOutputStream("path\\to\\config.properties",true)) {

    Properties prop = new Properties();

    // set the properties value
    prop.setProperty("IFCode", "34253");

    // save properties to project root folder
    prop.store(output, null);

    System.out.println(prop);

}  catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2011-11-19
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2014-04-07
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多