当属性在属性文件中重复时抛出异常 [英] Throw exception when a property is duplicated in a properties file

查看:54
本文介绍了当属性在属性文件中重复时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当属性文件包含重复属性时,如何抛出异常?以下是演示这种情况的示例:

How can I throw an Exception when a properties file contains a duplicate property? Here is an example demonstrating this situation:

# Properties-file

directory=D:\\media\\D-Downloads\\Errorfile\\TEST_A
directory=D:\\media\\D-Downloads\\Errorfile\\TEST_B
#directory=D:\\media\\D-Downloads\\Errorfile\\TEST_C

推荐答案

我想您正在使用类似 Properties.load() 的内容读取文件.它使用 put(key, value) 在内部设置参数.您可以覆盖该方法以获得所需的行为,例如

I suppose you are reading the file with something like Properties.load(). It sets the parameter internally using put(key, value). You can override that method to get the desired behaviour like e.g.

new Properties() {
    @Override
    public synchronized Object put(Object key, Object value) {
        if (get(key) != null) {
            throw new IllegalArgumentException(key + " already present.");
        }
        return super.put(key, value);
    }
}.load(...);

将其集成到 OP 的代码中:

Integrating this into the OP's code:

File propertiesFile = new File("D:/media/myProperties.properties");
Properties properties = new Properties() {
    @Override
    public synchronized Object put(Object key, Object value) {
        if (get(key) != null) {
            // or some other RuntimeException you like better...
            throw new IllegalArgumentException(key + " already present.");
        }
        return super.put(key, value);
    }
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile))) {
  properties.load(bis);

} catch (IllegalArgumentException ex) {
  //
}

顺便说一下,为什么要捕获异常?如果程序的配置已损坏,我不会继续该程序(可能在顶层捕获以记录事件).但异常处理是一个不同的话题...

By the way, why would you want to catch the exception? I'd not continue a program if its configuration is corrupt (maybe catching at top-level to log the event). But exception-handling is a different topic...

(我的原始代码示例没有编译,我更正了)

( my original code samles didn't compile, I corrected them)

这篇关于当属性在属性文件中重复时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆