An easy option is java.util.Properties
, which not only supports loading configuration data from key=value
and XML files, but also directly supports the hierarchical defaults you describe.
For example:
Properties base = new Properties();
base.load(new FileReader("base.cfg"));
Properties custom = new Properties(base);
custom.load(new FileReader("custom.cfg"));
// 'custom' defers to 'base' for properties that were not in "custom.cfg".
// custom.remove(key) can be used to restore a default from 'base'.
Note that Properties
does not have built-in support for grouped / hierarchical properties (e.g. an XML tree or an INI file with sections), but will generally get the job done in many cases.
It is possible to load the base configuration after the custom configuration as well if, for example, the custom configuration contains a property that specifies the base file name (this may be useful given some of your comments below):
Properties base = new Properties();
Properties custom = new Properties(base);
custom.load(new FileReader("custom.cfg"));
base.load(new FileReader(custom.getProperty("basefile")));
By the way, both libraries you mentioned (Apache Commons Configuration and ini4j) are in good working condition. The Apache library has support for a wider range of formats and is more actively maintained, but ini4j is mature (been around for about 10 years and INI files haven't changed) and also works well. I've personally used both a number of times and they have always delivered as promised.
All null / exception handling left out of examples for clarity.