Toti Toti - 3 years ago 175
Java Question

Throw exception when a property is duplicated in a properties file

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

Answer Source

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(...);

EDIT:

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...

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download