【问题标题】:Configure java.util.logging with apache commons-configuration PropertiesConfiguration?使用 apache commons-configuration PropertiesConfiguration 配置 java.util.logging?
【发布时间】:2013-10-29 17:45:02
【问题描述】:

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

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 提供的属性数组)

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      不。但是您可以将 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-11
        • 2013-03-25
        • 2012-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-29
        • 2013-02-26
        • 2012-12-13
        相关资源
        最近更新 更多