Since there is no concept of a section in the Properties
class, one would have to come up with some way to find the section of the property file which is wanted.
One possible approach would be to obtain the Set
of keys, and find the ones which contains the prefix which is wanted.
This would be like applying a filter on the keys of the property and picking out the keys which are desired. In this case, we can think of the prefix as being the dot-separated entry in the property file.
Here's a little sample code to demonstrate the overall idea:
Properties p = new Properties();
p.put("hello.world", "42");
p.put("hello.earth", "1");
p.put("abc.def", "3");
p.put("def.ghi", "5");
// Go through the keys in the property.
for (Object propKey : p.keySet()) {
String key = (String)propKey;
// Select the keys with the prefix "hello."
if (key.startsWith("hello.")) {
System.out.println(key + ", " + p.getProperty(key));
}
}
(The code is not very pleasant because Properies
is not genericized.)
Output:
hello.world, 42
hello.earth, 1
In the example above, the one did not load the entries from the an external properties file, but that can be achieved trivially using the Properties.load
method, as previously mentioned in the other answers.
A little bit of a different approach, where the keys are filtered by the desired prefix, then the information can be read through a simple for
loop.
Here's an example using the Collections2.filter
method from the Google Collections, which can filter a Collection
by a certain Predicate
. The filtered result (keys which have the desired prefix) is given to the for
loop in order to obtain the key and value pair:
Properties p = new Properties();
p.put("hello.world", "42");
p.put("hello.earth", "1");
p.put("abc.def", "3");
p.put("def.ghi", "5");
for (Object propKey : Collections2.filter(p.keySet(), new Predicate<Object>() {
public boolean apply(Object o) {
return ((String)o).startsWith("hello.");
}
}))
{
String key = (String) propKey;
System.out.println(key + ", " + p.getProperty(key));
}
This may be a little bit overkill, but it's another approach to implementing a filter to narrow down the properties with the desired keys.