4

我想好像 apache 的 commons-configuration 可能/支持从属性文件中获取属性作为地图

到目前为止,我已经设法使用以下代码片段间接地做到了这一点

 Map<String, T> map = new LinkedHashMap<>();
 Configuration subset = config.subset(key);
 if (!subset.isEmpty()) {
     Iterator it = subset.getKeys();
     while (it.hasNext()) {
         String k = (String) it.next();
         //noinspection unchecked
         T v = (T) subset.getProperty(k);
         map.put(k, v);
     }
 }
 return map;

有谁知道比这更直接的方法?

非常感谢

4

2 回答 2

6

我更喜欢你的做法,但如果你喜欢:ConfigurationMap

Map<Object,Object> config = new ConfigurationMap(subset);
于 2014-01-15T15:09:14.767 回答
0

to get all properties as Map with apache commons confuguration2

Parameters params = new Parameters();
File propertiesFile = new File("properties.properties");
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                        .configure(params.fileBased()
                        .setFile(propertiesFile)
                        .setEncoding("UTF-8"));

Configuration config = builder.getConfiguration();
Map<Object,Object> cfg = new ConfigurationMap(config);
cfg.entrySet();

to check out:

for (Map.Entry entry : cfg.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
于 2018-01-23T10:48:00.677 回答