A better class to update property files?

It doesn't get much better than Apache's Commons Configuration API. This provides a unified approach to configuration from Property files, XML, JNDI, JDBC datasources, etc.

It's handling of property files is very good. It allows you to generate a PropertiesConfigurationLayout object from your property which preserves as much information about your property file as possible (whitespaces, comments etc). When you save changes to the property file, these will be preserved as best as possible.


Sample code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.PropertiesConfigurationLayout;

public class PropertiesReader {
    public static void main(String args[]) throws ConfigurationException, FileNotFoundException {
        File file = new File(args[0] + ".properties");

        PropertiesConfiguration config = new PropertiesConfiguration();
        PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
        layout.load(new InputStreamReader(new FileInputStream(file)));

        config.setProperty("test", "testValue");
        layout.save(new FileWriter("path\\to\\properties\\file.properties", false));
    }
}

See also:

  • http://mvnrepository.com/artifact/commons-configuration/commons-configuration/
  • https://commons.apache.org/proper/commons-configuration/apidocs/org/apache/commons/configuration2/PropertiesConfigurationLayout.html

The sample code for using the Apache Commons Configuration library contributed by Patrick Boos is unnecessarily complicated. You don't need to use PropertiesConfigurationLayout explicitly unless you require some advanced control over the output. PropertiesConfiguration by itself is sufficient to preserve comments and formatting:

PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
config.setProperty("Foo", "Bar");
config.save();

(Note: This code works for the existing 1.10 stable version. I have not checked if it works on the 2.0 alpha builds currently available.)