Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Java property groups from a file

Is it possible to read different property groups from a Java file, without manual processing?

By "manual" I mean reading the file line by line, detecting where the start of a property group is and then extracting the corresponding key-value pairs. In practice, this means reinventing (most of) the wheel that the Properties.load() method constitutes.

Essentially, what I am looking for is an easy way of reading, from a single file, multiple groups of properties, with each group being identifiable, so that it can be loaded in its own Java Properties object.

like image 488
PNS Avatar asked Feb 24 '23 14:02

PNS


1 Answers

I you want to use java.util.Properties you can use prefixes. In .properties file:

group1.key1=valgroup1key1
group2.key1=valgroup2key1
group2.key2=valgroup2key2

and read them like this:

class PrefixedProperty extends Properties {
    public String getProperty(String group, String key) {
        return getProperty(group + '.' + key);
    }
}

and using:

/* loading, initialization like for java.util.Properties */
String val = prefixedProperty.getProperty("group1", "key1");

You can also use ini4j with windows ini files.

Another, better way is using own, custom structured file (for example XML).

like image 87
zacheusz Avatar answered Mar 08 '23 05:03

zacheusz