A better class to update property files?

后端 未结 8 1959
不思量自难忘°
不思量自难忘° 2020-12-01 10:27

Though java.util.properties allows reading and writing properties file, the writing does not preserve the formatting. Not surprising, because it is not tied to

相关标签:
8条回答
  • 2020-12-01 10:54

    The best answer contains a small mistake: The line:

    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    

    Must be replaced by:

    PropertiesConfigurationLayout layout = config.getLayout();
    
    0 讨论(0)
  • 2020-12-01 11:08

    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
    0 讨论(0)
提交回复
热议问题