java - 检查 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 个键相等时,我不想要覆盖逻辑
解决方案
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");
}
}
}
推荐阅读
- php - 使用 PDO 连接添加到新表的问题
- java - 我如何在 10 秒内实时获取蓝牙 rssi 10 次
- google-chrome-extension - 如何在 Chrome 的扩展中包含库
- java - Kafka Stream Scala API 性能缓慢
- performance - 在 Mysql 上使用 Spring Data JPA/Hibernate 进行批量/批量更新
- ios - 使用 Core Data 保存图像
- excel - 如何引用特定工作表与使用活动工作表?
- java - 为什么 MySQL JDBC 在我的 Maven 项目中不起作用?
- python - Django Rest Framework - JSON Post Request ManyTomany 字段问题
- javascript - 如何在 Chrome 中为 WebRTC 调用者设置远程描述而不会出错?