6

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.

Martin Schröder
  • 4,176
  • 7
  • 47
  • 81
Rachel
  • 1,131
  • 11
  • 26
  • 43

1 Answers1

7

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();
Dov Benyomin Sohacheski
  • 7,133
  • 7
  • 38
  • 64
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • "prop.store(out1,null);" is this the only way to writing a property file? – Rachel Mar 06 '13 at 10:33
  • it is specially designed method for saving Properties, what is special about it that it automatically converts chars to \uxxxx formmat when neecessary – Evgeniy Dorofeev Mar 06 '13 at 10:58
  • 1
    in properties file, the key and value should be in this format.. "key = jdbc:dbname:dbtype:host:port/SID,uname,pass".. but while writing with store() method, its adding escape sequences.. so now the key and value "key = jdbc\:dbname\:dbtype\:host\:port/SID,uname,pass"... how to write it without escape sequences.. – Rachel Mar 06 '13 at 11:36
  • this behavior is according to Properties API, it will read it back OK. Anyway, I added an example how to write Properties directly. – Evgeniy Dorofeev Mar 06 '13 at 12:07
  • thanks a lot.. its working.. but instead this, for(Entry e : props.entrySet()) { }, it should be, for(Entry e : prop.entrySet()) { } – Rachel Mar 06 '13 at 12:22