2013-04-23 21 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などをたとえば、以下の.propertiesファイルを持っている場合。ご存知のように、私は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 に? –

+0

Googleグアバを使用できます。 Lists.newArrayList(イテレータ) – tstorms

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 Commonsのバージョン< 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); 
} 

編集Apacheのコモンズバージョン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

+0

一般的な設定の2.1バージョンを探したので、PropertiesConfigurationのコンストラクタは引数を受け付けません。あなたはそれに応えるためにあなたの応答を更新していただけますか? – Scalable

+0

@Scalable編集の正当性を確認してください。 – NINCOMPOOP

関連する問題