获取属性文件 apache commons 中的条目数

Get number of entries in properties file apache commons

我正在创建要 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);
            }

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

根据文档,我认为您应该能够使用 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));