将数据附加到属性文件时,现有注释消失,数据顺序正在更改。请建议如何避免这种情况?
属性文件中的数据(追加数据前)和注释如下:
# 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();
}
}调用上述函数a,如下所示:
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我希望数据追加到最后,不想更改顺序,也不想删除之前输入的注释。请告诉我是否有可能实现我的要求?
发布于 2013-07-02 14:14:52
我最近遇到了同样的问题,在StackOverflow上找到了以下答案:https://stackoverflow.com/a/565996/1990089。它建议使用Apache Commons配置API来处理属性文件,这允许保留注释和空格。然而,我自己还没有尝试过。
发布于 2013-07-02 13:45:39
保留属性文件的注释并不直接。java.util.Properties上没有处理注释的方法。读取文件时,注释将被忽略。因为当我们执行properties.load时,只有键值对被加载,因此当您将其保存回来时,注释会丢失。检查下面的链接,有一个解决方案可以实现您需要的,但不是优雅的方式:
http://www.dreamincode.net/forums/topic/53734-java-code-to-modify-properties-file-and-preserve-comments/
发布于 2017-06-16 15:13:57
如果您不想从属性文件中删除您的内容。只需读取并替换文件中的字符串即可。
String file="D:\\path of your file\abc.properties";
Path path = Paths.get(file);
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("name=anything", "name=anything1");
Files.write(path, content.getBytes(charset));上面的代码不会从文件中删除内容。它只是替换了文件中的部分内容。
https://stackoverflow.com/questions/17418106
复制相似问题