如何将新数据附加到属性文件中的现有数据?
作者:互联网
我使用以下代码将数据写入属性文件
public void WritePropertiesFile(String key, String data)
{
Properties configProperty = new Properties();
configProperty.setProperty(key, data);
File file = new File("D:\\Helper.properties");
FileOutputStream fileOut = new FileOutputStream(file,true);
configProperty.store(fileOut, "sample properties");
fileOut.close();
}
I am calling the above method 3 times as follows:
help.WritePropertiesFile("appwrite1","write1");
help.WritePropertiesFile("appwrite2","write2");
help.WritePropertiesFile("appwrite3","write3");
但是,Helper.properties文件中的数据显示如下:
#sample properties
#Mon Jul 01 15:01:45 IST 2013
appwrite1=write1
#sample properties
#Mon Jul 01 15:01:45 IST 2013
appwrite2=write2
appwrite1=write1
#sample properties
#Mon Jul 01 15:01:45 IST 2013
appwrite3=write3
appwrite2=write2
appwrite1=write1
我希望数据附加到现有数据,并且不需要重复数据,如下所示:
appwrite3=write3
appwrite2=write2
appwrite1=write1
请建议怎么做?
解决方法:
只是不要在追加模式下打开文件.
您从文件中读取现有属性并再次写入它们.如果您追加到该文件,将追加Properties对象的所有内容,因为这是您要求的.
只需更换:
FileOutputStream fileOut = new FileOutputStream(file,true);
有:
FileOutputStream fileOut = new FileOutputStream(file);
旁注:您应该在finally块中关闭()输出流.
标签:java,properties-file 来源: https://codeday.me/bug/20191006/1862607.html