我遇到以下问题。我有一个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));
}
感谢您的帮助。
答案 0 :(得分:0)
如果您只关心用户名和密码,请尝试以下操作:
final Map<String, String> accounts = new HashMap<String, String>();
final File pwdFile = new File("path to your user/password file");
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(pwdFile));
br.readLine();// you don't need the first line
while (true)
{
String line = br.readLine();
if (line == null)
break;//end of file have been reached
final String user = line.split("=")[1].trim();
line = br.readLine();
if (line == null)// pwd is missing
throw new Exception("Invalid pwd file");
final String pwd = line.split("=")[1].trim();
accounts.put(user, pwd);
}
}
catch (final Exception e)
{
// add your own error handling code here
e.printStackTrace();
}
finally
{
if (br != null)
br.close();
}
此代码假设包含用户名的行后面会紧跟一行,其中包含上一行用户名的密码。