我需要使用apache-commons-configuration
编写一个简单的配置文件,但无论我尝试什么,它都不会写任何文件。
这就是文件的样子
<config>
<foo>bar</foo>
</config>
我正在编写foo配置:
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");
}
我错过了什么吗?在Apache Commons Configuration - File-based Configurations我无法看到设置文件所需的任何其他信息,所以我真的不知道我在这里失踪了什么。
由于某些原因,FileBasedConfiguration
没有自己设置xml文件,所以我必须手动创建它并设置根元素,如下所示:
configFilePath.toFile().createNewFile();
final Writer writer = Files.newBufferedWriter(configFilePath);
writer.write("<config></config>"); //sets the root element of the configuration file
writer.flush();
我不应该FileBasedConfiguration
为我处理此问题,或者这是apache-commons
未记录的步骤吗?