Delete entry from properties file

How to remove key and value from properties file? My properties file has the following contents:

key1=value1 key2=value2 

I used the code below to delete the key2=value2 entry. After that, the file has the following meanings:

 key1=value1 key2=value2 Wed Mar 06 12:36:32 IST 2013 key1=value1 

java code to delete entry:

 FileOutputStream out1 = new FileOutputStream(file, true); prop.remove(key); prop.store(out1,null); 

What a mistake I am making. How to clear all contents of a file before writing it.

+6
source share
1 answer

1) The contents of the properties file should look like this:

 key1=value1 key2=value2 

2) You open the file in add mode, this is wrong. It should be:

 new FileOutputStream(file); 

3) Close out1 explicitly, Properties.store API:

The output stream remains open after this method returns.

If you do not want to use Properties.store, you can directly write "Properties"

 PrintWriter pw = new PrintWriter("test.properties"); for(Entry e : props.entrySet()) { pw.println(e); } pw.close(); 
+7
source

All Articles