How to add new data to existing data in a property file?

I use the following code to write data to a 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"); 

However, the data in the 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 the data to be added to existing data and not want to duplicate the data, namely:

 appwrite3=write3 appwrite2=write2 appwrite1=write1 

Please suggest how to do this?

+6
source share
2 answers

Just do not open the file in add mode.

You read existing properties from the file and write them again. If you add to the file, the entire contents of the Properties object will be added, as this is what you requested.

Just replace:

 FileOutputStream fileOut = new FileOutputStream(file,true); 

with:

 FileOutputStream fileOut = new FileOutputStream(file); 

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

+7
source

I know that this was answered, but only for future code the link should look more or less:

 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"); } } 
+1
source

Source: https://habr.com/ru/post/948459/


All Articles