【问题标题】:Get number of entries in properties file apache commons获取属性文件apache commons中的条目数
【发布时间】:2020-03-30 03:06:14
【问题描述】:

我正在创建一个要 ping 的 IP 地址列表,用户可以将其添加到列表中,然后以 site.name1 = ... site.name2 = ... 的形式保存到属性文件中

目前我有一个固定数量的 for 循环,有没有办法获取属性文件中的条目数,以便我可以在 for 循环中设置它而不是等待异常?

 PropertiesConfiguration config = configs.properties(new File("IPs.properties"));
            //initially check for how many values there are - set to max increments for loop
            for (int i = 0; i < 3; i++) { //todo fix
                siteName = config.getString("site.name" + i);
                siteAddress = config.getString("site.address" + i);
                SiteList.add(i, siteName);
                IPList.add(i, siteAddress);
            }

我查看了文档和其他问题,但它们似乎无关。

【问题讨论】:

    标签: java properties apache-commons


    【解决方案1】:

    在我看来,根据文档,您应该能够使用 PropertiesConfiguration#getLayout#getKeys 将所有键的集合作为字符串。

    我不得不稍微修改一下代码以使用 apache-commons-configuration-1.10

            PropertiesConfiguration config = new PropertiesConfiguration("ips.properties");
    
            PropertiesConfigurationLayout layout = config.getLayout();
    
            String siteName = null;
    
            String siteAddress = null;
    
            for (String key : layout.getKeys()) {
                String value = config.getString(key);
    
                if (value == null) {
                    throw new IllegalStateException(String.format("No value found for key: %s", key));
                }
                if (key.equals("site.name")) {
                    siteName = value;
                } else if (key.equals("site.address")) {
                    siteAddress = value;
                } else {
                    throw new IllegalStateException(String.format("Unsupported key: %s", key));
                }
            }
            System.out.println(String.format("name=%s, address=%s", siteName, siteAddress));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 2023-03-16
      • 2021-09-05
      相关资源
      最近更新 更多