【发布时间】: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