I need to write a simple configuration file using apache-commons-configuration
but no matter what I try, it's not writing anything to the file.
This is how the file should look like
<config>
<foo>bar</foo>
</config>
This is what I'm doing to write the foo configuration:
private static final String USER_CONFIGURATION_FILE_NAME = "config.xml";
private final Path configFilePath = Paths.get(System.getProperty("user.home"), ".myapp",
USER_CONFIGURATION_FILE_NAME);
private final FileBasedConfigurationBuilder<XMLConfiguration> configBuilder=
new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
.configure(new Parameters().xml().setFile(configFilePath.toFile()));
/**
* Sets the foo configuration to the given {@link String}
*
* @param foo The configuration to be set up
* @throws ConfigurationException If any error occur while setting the property on the
* configuration file
*/
public void setfoo(final String bar) throws ConfigurationException {
checkNotNull(bar);
final Configuration config = configBuilder.getConfiguration();
config.setProperty("foo", bar);
configBuilder.save();
}
/**
* Retrieves the foo set up on the configuration file
*
* @return The foo set up on the configuration file
* @throws ConfigurationException If any error occur while setting the property on the
* configuration file
* @throws NoSuchElementException If there is no foo set up
*/
public String getFoo() throws ConfigurationException {
return configBuilder.getConfiguration().getString("foo");
}
Am I missing something? In Apache Commons Configuration - File-based Configurations I can't see any other information needed to set up the file, so I really don't know what I'm missing here.
For some reason the FileBasedConfiguration
is not setting up the xml file by itself, so I had to create it manually and set up the root element, like this:
configFilePath.toFile().createNewFile();
final Writer writer = Files.newBufferedWriter(configFilePath);
writer.write("<config></config>"); //sets the root element of the configuration file
writer.flush();
Shouldn't FileBasedConfiguration
take care of this for me, or this is a step that's not documented on apache-commons
?