如何将新数据附加到属性文件中的现有数据? [英] How to append new data to existing data in properties file?

查看:107
本文介绍了如何将新数据附加到属性文件中的现有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using following code for writing data to 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");

但是,Helper.properties文件中的数据显示如下:

However, the data in Helper.properties file is displayed as follows:

#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

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

I want data to append to existing data and doesn't want duplicate data, that is as follows:

appwrite3=write3
appwrite2=write2
appwrite1=write1

请建议怎么做?

推荐答案

只是不要以追加模式打开文件。

Just do not open the file in append mode.

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

You read existing properties from the file and the write them again. If you append to the file, all the contents of the Properties object will be appended since this is what you asked for.

只需替换:

FileOutputStream fileOut = new FileOutputStream(file,true);

with:

FileOutputStream fileOut = new FileOutputStream(file);

附注:你应该 .close()您的输出流在 finally 块中。

Side note: you should .close() your output stream in a finally block.

这篇关于如何将新数据附加到属性文件中的现有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆