Java: Read an unknown number of properties
I have a Java properties file defined as something like:
Property.1=value1
Property.2=value2
...
There could be any number of properties here.
I am familiar with how to read and use Java Properties, but I am not sure how I would code reading properties when I don't know the number of them. My idea of pseudo-code would be something like:
// Somehow get the number of properties
for (int i开发者_Go百科=0; i<properties.size(); i++ {
prop.getProperty("Property"+i);
...
}
Does anyone know how to read a variable number of properties?
If your properties are numbered sequentially as your example suggests:
int i = 1;
String p;
while ((p = prop.getProperty("Property."+i)) != null) {
// property #i has value p
i++;
}
The java.util.Properties
class has the ability to load from an input stream.
http://download.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.InputStream%29
Simply pass a new Properties
object the input stream from the file and let it roll.
You may want to take a look at Commons Collections class ExtendedProperties and it's method subset
That allows you to get all properties with given prefix ('Property.' for example)
精彩评论