如何将新数据附加到属性文件中的现有数据?

Vik*_*kas 7 java properties-file

我使用以下代码将数据写入属性文件

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");
Run Code Online (Sandbox Code Playgroud)

但是,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
Run Code Online (Sandbox Code Playgroud)

我希望数据附加到现有数据,并且不需要重复数据,如下所示:

appwrite3=write3
appwrite2=write2
appwrite1=write1
Run Code Online (Sandbox Code Playgroud)

请建议怎么做?

fge*_*fge 8

只是不要在追加模式下打开文件.

您从文件中读取现有属性并再次写入它们.如果您追加到该文件,Properties将附加该对象的所有内容,因为这是您要求的.

只需更换:

FileOutputStream fileOut = new FileOutputStream(file,true);
Run Code Online (Sandbox Code Playgroud)

有:

FileOutputStream fileOut = new FileOutputStream(file);
Run Code Online (Sandbox Code Playgroud)

旁注:您应该.close()finally块中输出流.