2013-10-31 61 views
0

- 方案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); 
} 

,但問題是我沒有上的按鍵數量的任何想法。我不能拉所有的價值,因爲會有其他我不想要的鑰匙。

對此有何想法?

+1

你可以使用一個單一的屬性值和使用分隔符來分割。像「template.lo =規則A |模板B,規則B |模板X,規則C |模板M」 – Todoy

回答

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; 
} 

這是假設沒有屬性列表中(如:template.lo1=.., template.lo3=...

3

jav.util.PropertiespropertyNames()

如果相同名稱的關鍵尚未從主屬性中找到返回屬性列表中所有鍵,包括默認屬性列表中不同的鍵的枚舉名單。

你可以遍歷它們,只取得你需要的。

還有stringPropertyNames()

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; 
}