java - 将数据附加到属性文件,注释消失,数据顺序改变

标签 java properties-file

<分区>

将数据附加到属性文件时,现有注释消失并且数据顺序正在更改。请建议如何避免它?

属性文件中的数据(附加数据之前)以及注释如下:

# Setting the following parameters 
# Set URL to test the scripts against
App.URL = https://www.gmail.com
# Enter username and password values for the above Test URL
App.Username = XXXX
App.Password = XXXX

我正在向上述属性文件添加更多数据,如下所示:

 public void WritePropertiesFile(String key, String data) throws Exception
{       
    try 
    {
        loadProperties();  
        configProperty.setProperty(key, data);
        File file = new File("D:\\Helper.properties");
        FileOutputStream fileOut = new FileOutputStream(file);
        configProperty.store(fileOut, null);
        fileOut.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

将上述函数调用为:

help.WritePropertiesFile("appwrite1","write1");
help.WritePropertiesFile("appwrite2","write2");
help.WritePropertiesFile("appwrite3","write3");

数据添加成功,但是之前输入的注释消失了,数据的顺序也改变了,属性文件(追加数据后)显示如下

#Tue Jul 02 11:04:29 IST 2013
App.Password=XXXX
App.URL=https\://www.gmail.com
appwrite3=write3
appwrite2=write2
appwrite1=write1
App.Username=XXXX

我希望数据追加在最后,不想改变顺序,也不想删除之前输入的注释。请让我知道是否可以实现我的要求?

最佳答案

我最近遇到了同样的问题,并在 StackOverflow 上找到了以下答案:https://stackoverflow.com/a/565996/1990089 .它建议使用 Apache Commons Configuration API 来处理属性文件,这样可以保留注释和空格。不过,我自己还没有尝试过。

关于java - 将数据附加到属性文件,注释消失,数据顺序改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17418106/

相关文章:

java - 如何创建可重用的测试代码而不创建循环依赖项?

java - 使用 URLConnection 发送和检索 map

tomcat - 在生产环境中访问 i18n 属性

java - 在 Google App Engine 中配置 .Properties 文件

c# - 用于跨平台应用程序的 Python + QT、Windows Forms 或 Swing?

java - 在android中创建自定义 map

java - 如何在没有属性文件的情况下使用 Spring 的 @Value?

java - SPRING MVC - 使用外部文件作为@PropertySource

java - 如何在 Eclipse 中运行示例 Android SDK 应用程序?

java - Eclipse 和 .properties 文件中的不同构建配置