当 属性 在属性文件中重复时抛出异常

Throw exception when a property is duplicated in a properties file

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

# 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) 在内部设置参数。您可以覆盖该方法以获得所需的行为,例如

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 的代码中:

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) {
  //
}

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

(编辑:我的原始代码样本没有编译,我更正了它们)

Ralf Kleberhoff 的回答是正确的; 但是,我不会使用匿名 class。 您似乎想多次使用此功能, 所以我会创建一个扩展 Properties 的 class 并像 Ralf

一样覆盖 put

请注意,put 方法来自 Hashtable class Properties 扩展。

这里有一个例子(我没有尝试编译它):

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

        super.put(key, value);
    }
}

这是我加载属性的方式:

        File propertiesFile = new File("D:/media/myProperties.properties");
    Properties properties = new Properties();
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile))) {
      properties.load(bis);

    } catch (Exception ex) {
      //
    }

@Ralf 我该如何修改你的代码?

如此处所述Tool to find duplicate keys and value in properties file

” 我使用了两个不错的工具

unival npm 包:这是一个命令行工具,用于检测重复的键、值或行。

安装包的 npm 命令:npm i unival

Link: https://www.npmjs.com/package/unival

unival 扩展:如果您使用 vscode,这是一个非常有用的扩展,可以即时检测重复项。 “

最好的方法是对 运行 unival 命令进行测试,这将防止重复值进入属性文件