How to append new data to existing data in properties file?

巧了我就是萌 提交于 2019-12-04 05:12:25

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.

Just replace:

FileOutputStream fileOut = new FileOutputStream(file,true);

with:

FileOutputStream fileOut = new FileOutputStream(file);

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

I know this has been answered, but just for future reference code should look more-less like this:

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");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!