Search code examples
javaapache-commons-config

Apache commons config: Generate configuration file from defaults


I want to distribute my application in one jar. That means that I do not want to ship any external files with it, that also includes that I do not want to ship the default configuration file with my project.

I could for sure build the basic XML structure with a implementation of JDOM2 or copy it out of the classpath onto the file system, but is there a out-of-the-box variant implemented by Commons Configuration?

I have only found online documentation that explains reading and handling already existing configuration files.

I would imagine this code taking in a number of Key -> Value Pairs and then generating a new config, is this possible?

Please do not offer me any alternatives to a XML file, please answer this question specifically to the implementation I asked about. If you know about any, you can suggest a alternative to Commons Configuration that does what I need to do.


Solution

  • What about, e.g.?

    XMLConfiguration config = new XMLConfiguration();
    config.addProperty("test.dir[@name]", "C:\\Temp\\");
    config.addProperty("test.dir[@name]", "D:\\Data\\");
    config.setFilename("yourfilename.xml");
    config.save();
    

    See all known implementing classes of: https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/org/apache/commons/configuration/FileConfiguration.html

    And https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/org/apache/commons/configuration/XMLConfiguration.html for an example.