首页 > 解决方案 > 检查 java 属性文件中键值的唯一性

问题描述

我想将一定数量的属性文件加载到同一个 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");
        }
    }
}

}

并拥有此属性文件:

调度程序属性

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

k.属性

prop1=BLABLA

y.properties

prop2=BLEBLE

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

k.属性

prop1=BLABLA

y.properties

prop1=BLEBLE

编辑

它与这篇文章加载多个属性文件相同,但当 2 个键相等时,我不想要覆盖逻辑

标签: javaproperties

解决方案


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");
        }
    }
}

推荐阅读