2013-04-23 38 views
6

我需要獲取.properties文件中的屬性列表。例如,如果有以下屬性文件:如何使用apache.commons獲取屬性列表

users.admin.keywords = admin 
users.admin.regexps = test-5,test-7 
users.admin.rules = users.admin.keywords,users.admin.regexps 

users.root.keywords = newKeyWordq 
users.root.regexps = asdasd,\u0432[\u044By][\u0448s]\u043B\u0438\u0442[\u0435e] 
users.root.rules = users.root.keywords,users.root.regexps,rules.creditcards 

users.guest.keywords = guest 
users.guest.regexps = * 
users.guest.rules = users.guest.keywords,users.guest.regexps,rules.creditcards 

rules.cc.creditcards = 1234123412341234,11231123123123123,ca 
rules.common.regexps = pas 
rules.common.keywords = asd 

而作爲一個結果,我想獲得它由這樣的字段名稱的ArrayList: users.admin.keywords, users.admin.regexps, users.admin.rules等。正如你已經注意到了,我要做到這一點使用apache.commons.config

回答

13

您可以按以下使用:

Configuration configuration = new PropertiesConfiguration(filename); 
Iterator<String> keys = configuration.getKeys(); 
List<String> keyList = new ArrayList<String>(); 
while(keys.hasNext()) { 
    keyList.add(keys.next()); 
} 
2

您可以使用getKeys()

它返回的屬性文件中所有鍵的Iterator<String>

+0

而如何從迭代器轉換到ArrayList ? – 2013-04-23 12:09:37

+0

你可以使用谷歌番石榴,例如Lists.newArrayList(迭代器)。 – tstorms 2013-04-23 12:22:18

3
Properties prop = new Properties(); 
prop.load(new FileInputStream("prop.properties")); 
Set<Map.Entry<Object, Object>> set = prop.entrySet(); 
List<Object> list = new ArrayList<>(); 
for (Map.Entry<Object, Object> entry : prop.entrySet()) 
{ 
    list.add(entry.getKey()); 
} 
System.out.println(list); 

使用Apache共享版< 2.1:

Configuration config = new PropertiesConfiguration("prop.properties"); 
List<String> list = new ArrayList<>(); 
Iterator<String> keys = config.getKeys(); 
while(keys.hasNext()){ 
    String key = (String) keys.next(); 
    list.add(key); 
} 

編輯的阿帕奇百科全書2.1版:

List<String> list = new ArrayList<>(); 
Parameters params = new Parameters(); 
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = 
    new FileBasedConfigurationBuilder<FileBasedConfiguration> 
    (PropertiesConfiguration.class) 
    .configure(params.properties() 
    .setFileName("prop.properties")); 
try 
{ 
    Configuration config = builder.getConfiguration(); 
    Iterator<String> keys = config.getKeys(); 
    while(keys.hasNext()){ 
     String key = (String) keys.next(); 
     list.add(key); 
    } 
} 
catch(ConfigurationException cex) 
{ 
    // handle exception here 
} 
+0

請參閱編輯的回覆! – NINCOMPOOP 2013-04-23 12:20:46

+0

當我查找2.1版本的通用配置時,PropertiesConfiguration的構造函數不接受任何參數。你能否更新你的反應來迎合? – Scalable 2016-08-23 21:04:01

+0

@Scalable請驗證編輯的正確性。 – NINCOMPOOP 2016-08-30 16:17:00