【问题标题】:How to get list of properties using apache.commons如何使用 apache.commons 获取属性列表
【发布时间】:2013-04-16 15:18:17
【问题描述】:

我需要获取 .properties 文件中的属性列表。例如,如果有以下 .properties 文件:

users.admin.keywords = admin
users.admin.regexps = test-5,test-7
users.admin.rules = users.admin.keywords,users.admin.regexps

users.root.keywords = newKeyWordq
users.root.regexps = asdasd,\u0432[\u044By][\u0448s]\u043B\u0438\u0442[\u0435e]
users.root.rules = users.root.keywords,users.root.regexps,rules.creditcards

users.guest.keywords = guest
users.guest.regexps = *
users.guest.rules = users.guest.keywords,users.guest.regexps,rules.creditcards

rules.cc.creditcards = 1234123412341234,11231123123123123,ca
rules.common.regexps = pas
rules.common.keywords = asd

因此,我想获得一个 ArrayList,其中包含如下字段的名称: users.admin.keywords, users.admin.regexps, users.admin.rules 等等。正如您所注意到的,我需要使用 apache.commons.config 来执行此操作

【问题讨论】:

    标签: java apache-commons-config


    【解决方案1】:

    您可以使用getKeys()

    它在属性文件中的所有键上返回一个Iterator<String>

    【讨论】:

    • 以及如何从iterator转换为ArrayList
    • 你可以使用谷歌番石榴,例如Lists.newArrayList(Iterator).
    【解决方案2】:
    Properties prop = new Properties();
    prop.load(new FileInputStream("prop.properties"));
    Set<Map.Entry<Object, Object>> set = prop.entrySet();
    List<Object> list = new ArrayList<>();
    for (Map.Entry<Object, Object> entry : prop.entrySet())
    {
       list.add(entry.getKey());
    }
    System.out.println(list);
    

    使用 Apache Commons 版本

    Configuration config = new PropertiesConfiguration("prop.properties");
    List<String> list = new ArrayList<>();
    Iterator<String> keys = config.getKeys();
    while(keys.hasNext()){
        String key = (String) keys.next();
        list.add(key);
    }
    

    针对 Apache Commons 版本 2.1 编辑:

    List<String> list = new ArrayList<>();
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
        new FileBasedConfigurationBuilder<FileBasedConfiguration>
        (PropertiesConfiguration.class)
        .configure(params.properties()
        .setFileName("prop.properties"));
    try
    {
        Configuration config = builder.getConfiguration();
        Iterator<String> keys = config.getKeys();
        while(keys.hasNext()){
          String key = (String) keys.next();
          list.add(key);
        }
    }
    catch(ConfigurationException cex)
    {
        // handle exception here
    }
    

    【讨论】:

      【解决方案3】:

      你可以如下使用:

      Configuration configuration = new PropertiesConfiguration(filename);
      Iterator<String> keys = configuration.getKeys();
      List<String> keyList = new ArrayList<String>();
      while(keys.hasNext()) {
          keyList.add(keys.next());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 2019-11-15
        • 2023-03-13
        相关资源
        最近更新 更多