【发布时间】:2014-10-06 15:50:25
【问题描述】:
我遇到以下问题。我有一个configuration.properties 文件,我想在我的应用程序中读取它。它的形式如下:
accountNames = account1, account2, account3
account1.userName = testUserName
account1.password = testUserPassword
account2.userName = secondTestUserName
account2.password = secondTestUserPassword
account2.userName = thirdTestUserName
account2.password = thirdTestUserPassword
如何读取所有帐户并将 userName-userPassword 对存储在 HashMap 中?如我所见,我有一个二维数组。我对访问帐户每个属性的代码特别感兴趣。
编辑:我已将configuration.properties 文件更改为以下格式:
userNames = testUserName, secondTestUserName, thirdTestUserName
testUserName = testUserPassword
secondTestUserName = secondTestUserPassword
thirdTestUserName = thirdTestUserPassword
处理此问题的代码如下:
properties.load(new FileInputStream(configFilePath));
for(String s : properties.getProperty("userNames").split(",")){
clientCredentials.put(s.trim(), properties.getProperty(s.trim()));
}
//test:
for(String s:clientCredentials.keySet()){
System.out.println("Key: "+s+" & value: "+clientCredentials.get(s));
}
感谢您的帮助。
【问题讨论】:
-
您对不同的值使用相同的名称。这是不正确的。
-
但是如果帐户有 2 个或更多属性,我如何独立访问它们?
-
为什么不像
firstUserName = firstUserPassword那样只配对用户名和密码? -
我想到了这一点并找到了一个示例,但是如果每个帐户有超过 2 个属性(例如添加帐户的电子邮件),您该怎么办?您如何应对这种情况?
-
你想如何将它存储在 HashMap 中?如果您想使用第一列作为键,这是不正确的。
标签: java properties-file