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

时间:2013-07-01 09:41:45

标签: 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");

但是,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

请建议怎么做?

2 个答案:

答案 0 :(得分:8)

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

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

只需替换:

FileOutputStream fileOut = new FileOutputStream(file,true);

使用:

FileOutputStream fileOut = new FileOutputStream(file);

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

答案 1 :(得分:2)

我知道这已经得到了解答,但仅仅为了将来的参考代码看起来应该更像这样:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

class WritePropertiesFile {

    public void WritePropertiesFile(String key, String data) {
        FileOutputStream fileOut = null;
        FileInputStream fileIn = null;
        try {
            Properties configProperty = new Properties();

            File file = new File("D:\\Helper.properties");
            fileIn = new FileInputStream(file);
            configProperty.load(fileIn);
            configProperty.setProperty(key, data);
            fileOut = new FileOutputStream(file);
            configProperty.store(fileOut, "sample properties");

        } catch (Exception ex) {
            Logger.getLogger(WritePropertiesFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            try {
                fileOut.close();
            } catch (IOException ex) {
                Logger.getLogger(WritePropertiesFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        WritePropertiesFile help = new WritePropertiesFile();
        help.WritePropertiesFile("appwrite1", "write1");
        help.WritePropertiesFile("appwrite2", "write2");
        help.WritePropertiesFile("appwrite3", "write3");
    }
}