8

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

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

请建议怎么做?

4

2 回答 2

9

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

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

只需更换:

FileOutputStream fileOut = new FileOutputStream(file,true);

和:

FileOutputStream fileOut = new FileOutputStream(file);

旁注:您应该.close()将输出流放在一个finally块中。

于 2013-07-01T09:43:17.003 回答
3

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

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");
    }
}
于 2014-10-31T09:58:41.363 回答