Arashsoft Arashsoft - 8 days ago 9
Java Question

Cannot delete the key from java properties file

I read a properties file, delete a key from it with

remove()
and everything is fine until this step. But, when I try to use
store()
to save the properties into the file. It does not remove the key from properties file.

Here is my code:

Properties props = new Properties();
try (InputStream in = Files.newInputStream(Paths.get("/myFolder/myFile.properties"))){
props.load(in);
}catch(NoSuchFileException e){
// file not found, continue with empty Properties
}
props.remove("someKeyToDelete");

try (OutputStream out = Files.newOutputStream(Paths.get("/myFolder/myFile.properties"), StandardOpenOption.CREATE)){
props.store(out, null);
}


And this is inside myFile.properties:

someKeyToDelete=123


Also, If I run the code with this file:

key1.abc=abc
someKeyToDelete=123
key1.abc2=abc2


And I get this result !!:

key1.abc=abc
key1.abc2=abc2
123
key1.abc2=abc2

Answer

Use StandardOpenOption.TRUNCATE_EXISTING instead of StandardOpenOption.CREATE

From docs

If the file already exists and it is opened for WRITE access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.

I changed it to TRUNCATE_EXISTING

    try (OutputStream out = Files.newOutputStream(Paths.get("props2.properties"), StandardOpenOption.TRUNCATE_EXISTING)) {
        props.store(out, null);
    }

it created properties file as expected

#Tue Nov 29 22:39:04 IST 2016
key1.abc=abc
key1.abc2=abc2

Tried it on Ubuntu + Java8,it worked

Linux ubuntu 3.19.0-25-generic #26~14.04.1-Ubuntu SMP Fri Jul 24 21:16:20 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux