使用apache commons-configuration PropertiesConfiguration配置java.util.logging?

时间:2013-10-23 02:15:23

标签: java apache-commons java.util.logging

我想加载属性文件和命令行参数,然后在运行时动态配置日志记录,我之前可以这样做:

Properties configuration;
...

ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteArrayInputStream is;
byte[] buf;
try {
    configuration.store(os, "logging");
    buf = os.toByteArray();
    is = new ByteArrayInputStream(buf);
    java.util.logging.LogManager.getLogManager().readConfiguration(is);
} catch (IOException e) {
    System.err.println("Failed to configure java.util.logging.LogManager");
}

使用Properties很好但可以使用PropertiesConfiguration完成吗?

(仅供参考我希望利用commons-configuration提供的属性数组)

2 个答案:

答案 0 :(得分:1)

使用ConfigurationConverter将PropertiesConfiguration转换为标准属性文件

答案 1 :(得分:0)

不。但您可以将PropertiesConfiguration转换为Properties

public static Properties configurationAsProperties(){
    Properties fromConfiguration = new Properties();
    Iterator<String> keys = configuration.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        String value = asString(configuration.getProperty(key));
        fromConfiguration.setProperty(key,value);
        // System.out.println(key + " = " + value);
    }
    return fromConfiguration;
}

只是不要丢失那些逗号分隔值(configuration.getString只返回第一个)

private static String asString(Object value) {
    if (value instanceof List) {
        List<?> list = (List<?>) value;
        value = StringUtils.join(list.iterator(), ",");
    }
    return (String) value;
}