【问题标题】:Cheking uniqueness of key values in java properties files检查java属性文件中键值的唯一性
【发布时间】:2020-01-02 14:24:20
【问题描述】:

我想将一定数量的属性文件加载到同一个 java.util.Properties 对象中。我使用以下代码正确实现了这一点:

public class GloalPropReader {

public static final Properties DISPATCHER = new Properties();
public static final Properties GLOBAL_PROP = new Properties();

public GloalPropReader() {
    try (InputStream input = GloalPropReader.class.getClassLoader().getResourceAsStream("dispatcher.properties")) {
        DISPATCHER.load(input);
    } catch (IOException ex) {
        throw new RuntimeException("Can't access dispatcher information");
    }

    for (Object nth : DISPATCHER.keySet()) {
        String nthKey = (String) nth;
        String nthPathToOtherProps = (String) DISPATCHER.get(nthKey);
        Path p = Paths.get(nthPathToOtherProps);
        try (InputStream input = new FileInputStream(p.toFile())) {
            GLOBAL_PROP.load(input);
        } catch (IOException ex) {
            throw new RuntimeException("Can't access " + nthPathToOtherProps + " information");
        }
    }
}

}

并且拥有这个属性文件:

dispatcher.properties

path_to_prop_1=C:/Users/U/Desktop/k.properties
path_to_prop_2=C:/Users/U/Desktop/y.properties

k.properties

prop1=BLABLA

y.properties

prop2=BLEBLE

但我想要实现的是如果 2 个属性文件内部具有相同的键,则抛出 RuntimeException。例如,如果 k.properties 和 y.properties 如此,我希望这个类抛出异常

k.properties

prop1=BLABLA

y.properties

prop1=BLEBLE

编辑

这与这篇文章 Loading multiple properties files 相同,但我不希望 2 个键相等时的覆盖逻辑

【问题讨论】:

  • 为什么?很容易安排它们,如果它们都存在,则一个覆盖另一个。
  • 我不希望有人覆盖它们...可能覆盖它是一个错误,可能会导致该软件出现一种时髦且无法理解的行为

标签: java properties


【解决方案1】:
public static class GloalPropReader {
    private final Properties K_PROPERTIES = new Properties();
    private final Properties Y_PROPERTIES = new Properties();

    public GloalPropReader() {
        loadProperties("k.properties", K_PROPERTIES);

        loadProperties("y.properties", Y_PROPERTIES);

        Set intersection = new HashSet(K_PROPERTIES.keySet());
        intersection.retainAll(Y_PROPERTIES.keySet());
        if (!intersection.isEmpty()) {
            throw new IllegalStateException("Property intersection detected " + intersection);
        }
    }

    private void loadProperties(String name, Properties y_properties) {
        try (InputStream input = GloalPropReader.class.getClassLoader().getResourceAsStream(name)) {
            y_properties.load(input);
        } catch (IOException ex) {
            throw new RuntimeException("Can't access dispatcher information");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多