【问题标题】:Reading usernames and passwords for several accounts from .properties file从 .properties 文件中读取多个帐户的用户名和密码
【发布时间】: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


【解决方案1】:

如果您只关心用户名和密码,请尝试以下操作:

    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();

    }

此代码假定包含用户名的行后面将紧跟一行包含前一行用户名的密码的行。

【讨论】:

  • 对于常规文本文件,这是一个很好的做法,但对于 configuration.properties,我希望从 Properties 类的 load(InputStream inStream) 方法开始。
  • 因为您希望它在HashMap 中,所以使用此代码更容易、更快捷。否则,您将不得不使用 Properties.load 加载文件,然后迭代 Properties 对象的其他每个元素。第二个优点是您可以在加载文件时应用一些自定义格式(修剪,大写,...)
猜你喜欢
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2018-01-10
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多