0

My property file has properties like below:

#property1=
property2=asd

Is there a proper way to un comment and change the property1? I was looking at Apache Commons but there seems to be no non-ugly way to do this. The following wont work as the commented out property wont be read in the first place.

        PropertiesConfiguration config = new PropertiesConfiguration();
        PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
        layout.load(new InputStreamReader(new FileInputStream(new File(filePath))));
        config.setProperty("#property1", "new_value");
        FileWriter propsFile = new FileWriter(filePath, false);
        layout.save(propsFile);
Tim Falony
  • 125
  • 3
  • 13

2 Answers2

0

I assume you are looking for a way to do this in code, not with an editor.

If you read in the property file to java.util.Properties, the comments are all lost.

Your best bet is to read the property file into a String and update the string using a regex replace.

String newProperties = properties.replaceAll("^#*\s*property1=", "property1=");
Properties props = new Properties();
props.load(new StringReader(newProperties));
Joe Kampf
  • 339
  • 2
  • 8
0

Expanding on what @garnulf said, you want to do config.setProperty("property1", "new_value");

You aren't "uncommenting" the property value, but rather adding the property to your configuration at runtime. The file will not be changed.

Your configuration will not include the commented out property when you first load it (because it is commented out). When you call config.setProperty it will be added to your config.

Adam
  • 2,214
  • 1
  • 15
  • 26
  • unfortunately I don't want this behavior. I just need to update the commented out property than add one at the end of the file – Tim Falony Aug 25 '16 at 17:43
  • Are saying you want to write to your properties file programmatically? Do you want the properties to then take effect in your Java program? – Adam Aug 25 '16 at 18:11