- 情景1 -
这是我的属性文件:
template.lo=rule A | template B
template.lo=rule B | template X
template.lo=rule C | template M
template.lo=rule D | template G
我不认为上面的设计是允许的,因为有重复的键
- 情景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
绝对允许上述设计。
我想从Java中检索值,因此我将传入密钥以获取值。通常,我会用这种方式:
PropertyManager.getValue("template.lo1",null);
问题是关键会继续增加,上面的例子得到4 ...将来可能会有5或10个。
所以,我的问题是,我将如何检索所有值?
如果我知道总共有10个键,我可以这样使用:
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);
}
但问题是我对键的数量一无所知。我无法提取所有值,因为会有其他我不想要的键。
对此有什么想法吗?
答案 0 :(得分:3)
jav.util.Properties
有propertyNames()
:
返回此属性列表中所有键的枚举,如果尚未从主属性列表中找到相同名称的键,则在默认属性列表中包含不同的键。
你可以循环使用它们,只带你需要的那些。
答案 1 :(得分:0)
我会尝试获取属性,直到我得到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;
}
这假设属性列表中没有 hole (例如:template.lo1=.., template.lo3=...
)
答案 2 :(得分:0)
ResourceBundle是我之前用于属性文件的内容。
如果您查看API,您应该能够找到如何为您的文件创建ResourceBundle。
然后有一个containsKey(String)
方法可以用作循环条件。
所以你会使用以下内容:
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;
}