如何使用Apache Commons Configuration2从InputStream读取数据?

FileBasedConfigurationBuilder<XMLConfiguration> builder =
    new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
        .configure(
            new Parameters()
            .xml()
            .setFileName("")
            .setExpressionEngine(new XPathExpressionEngine())
        );

XMLConfiguration config = builder.getConfiguration();
config.read(sourceJarFile.getInputStream(sourcePropertiesEntry))

给出上面的代码,如果给setFileName空字符串,我将得到下面的异常。
org.apache.commons.configuration2.ex.ConfigurationException: Could not locate: org.apache.commons.configuration2.io.FileLocator@61dc03ce[fileName=tmp.xml,basePath=<null>,sourceURL=,encoding=<null>,fileSystem=<null>,locationStrategy=<null>]
at org.apache.commons.configuration2.io.FileLocatorUtils.locateOrThrow(FileLocatorUtils.java:346)
at org.apache.commons.configuration2.io.FileHandler.load(FileHandler.java:972)
at org.apache.commons.configuration2.io.FileHandler.load(FileHandler.java:702)
at org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder.initFileHandler(FileBasedConfigurationBuilder.java:312)
at org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder.initResultInstance(FileBasedConfigurationBuilder.java:291)
at org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder.initResultInstance(FileBasedConfigurationBuilder.java:60)
at org.apache.commons.configuration2.builder.BasicConfigurationBuilder.createResult(BasicConfigurationBuilder.java:421)
at org.apache.commons.configuration2.builder.BasicConfigurationBuilder.getConfiguration(BasicConfigurationBuilder.java:285)
at com.test.installer.App.getXMLConfigurationProperties(App.java:185)

如果我给出null或只是不调用setFileName();我将在read()行收到无法加载配置异常的信息。
org.apache.commons.configuration2.ex.ConfigurationException: Unable to load the configuration
    at org.apache.commons.configuration2.XMLConfiguration.load(XMLConfiguration.java:986)
    at org.apache.commons.configuration2.XMLConfiguration.read(XMLConfiguration.java:954)
    at com.test.installer.App.updateExistedProperties(App.java:84)

最佳答案

example in the API documentation:

设置文件参数(编码等):

   FileBasedBuilderParameters fileparams = ...
   FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                    new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(fileparams);

然后:
FileBasedConfiguration config = builder.getConfiguration();
FileHandler fileHandler = new FileHandler(config);
Inputstream istream = ...
fileHandler.load(istream);

请注意,您不能与此同时使用自动保存。为了保存,您可能需要提供一个OutputStream。就像是:
fh.save(ostream)

10-07 22:30