Reputation: 35
-- Scenario 1 --
This is my property file:
template.lo=rule A | template B
template.lo=rule B | template X
template.lo=rule C | template M
template.lo=rule D | template G
I dont think the above design is allowed since there's duplicate keys
-- Scenario 2 --
template.lo1=rule A | template B
template.lo2=rule B | template X
template.lo3=rule C | template M
template.lo4=rule D | template G
The above design is definitely allowed.
I want to retrieve values from Java, so I'll pass in the key to get the value. Normally, I'll use this way:
PropertyManager.getValue("template.lo1",null);
The problem is the key will keep on increasing, the above example got 4... in the future there might be 5 or 10.
So, my question is, how am I going to retrieve all the values?
If i know that there are 10 keys in total, I can use this way:
List <String> valueList = new ArrayList<String>();
for(int i = 1; i<totalNumberOfKeys+1; i++{
String value = (String) PropertyManager.getValue("template.lo"+i,null)
valueList.add(value);
}
but the problem is I dont have any idea on the number of keys. I cannot pull all the values since there will be other keys which i dont want.
Any idea on this?
Upvotes: 0
Views: 303
Reputation: 2764
ResourceBundle is what I've used previously for properties files.
If you check out the API you should be able to find how to create a ResourceBundle for you file.
Then there is a containsKey(String)
method that you could use as your loop condition.
So you would use something like the following:
ResourceBundle bundle = new ResourceBundle();
bundle.getBundle("My/File/Name");
List <String> valueList = new ArrayList<String>();
int i = 1;
String propertyKey = "template.lo" + i;
while( bundle.containsKey(propertyKey) ) {
valueList.add((String) bundle.getObject(propertyKey));
i++;
propertyKey = "template.lo" + i;
}
Upvotes: 0
Reputation: 9301
I'd try to get the properties until I got null
:
public List<String> getPropertyValues(String prefix) {
List<String> values = new ArrayList<>();
for(int i=1;;i++) {
String value = (String) PropertyManager.getValue(prefix + i, null);
if(value == null){
break;
}
values.add(value);
}
return values;
}
This assumes there are no holes in the property list (like: template.lo1=.., template.lo3=...
)
Upvotes: 0
Reputation:
jav.util.Properties
has propertyNames()
:
Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.
You can loop over them and take only those you need.
There is also stringPropertyNames()
.
Upvotes: 3