Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an entry from property file

How to delete key and value from property file? My property file has these contents:

key1=value1 
key2=value2

I used the below code to delete the entry key2=value2. After that, now the file has these values:

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

java code to remove an entry:

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

What is the mistake am doing. How to clear the whole content of the file before writing it.

like image 894
Rachel Avatar asked Mar 06 '13 07:03

Rachel


1 Answers

1) The property file contents should look as follows:

key1=value1
key2=value2

2) You are opening the file in append 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 dont want to use Properties.store, you can write Properties directly

PrintWriter pw = new PrintWriter("test.properties");
for(Entry e : props.entrySet()) {
    pw.println(e);
}
pw.close();
like image 85
Evgeniy Dorofeev Avatar answered Oct 17 '22 20:10

Evgeniy Dorofeev