首页 > 解决方案 > 记事本到 HashMap-Java

问题描述

我编写了一个小程序,它根据提供的用户类型 Admin/Customer 从文本文件中读取并打印单个 ID 和密码,这是有效的。下面的代码

public class TextReader {

    //A method to load properties file
    public static Properties readProp() throws IOException {
        Properties prop = new Properties();
        FileInputStream file = new FileInputStream("C:\\Users\\config.text");
        prop.load(file);

        return prop;
    }

    //Read the file using method above
    public static void getUser(String userType) throws IOException {
        Properties prop = readProp();
        String userName=prop.getProperty(userType+ "_User");
        String userPassword=prop.getProperty(userType+ "_Psd");

        System.out.println(" The user is " + userName + " password " + userPassword);
    }

    public static void main(String[] args) throws IOException {
        getUser("Admin");
    }
}

测试文件:

Admin_User=jjones@adm.com
Admin_Psd=test123


Cust_User=kim@cust.com
Cust_Psd=test123

我想修改它,以便我现在可以将它们添加到 HashMap。所以我删除了 userType 参数

public static void getUser() throws IOException {
        Properties prop = readProp();
        String userName = prop.getProperty("_User");
        String userPassword = prop.getProperty("_Psd");

        HashMap<String, String> hmp = new HashMap<String, String>();
        hmp.put(userName, userPassword);

        for (Map.Entry<String, String> credentials : hmp.entrySet()) {
            System.out.println(credentials.getKey() + " " + credentials.getValue());
        }

        //System.out.println(" The user is " + userName + " password " + userPassword);
    }

我得到 null null 作为输出。我想不出办法让它们进入 HashMap,我可以使用一些提示/帮助。

Expected output: user name, password as key value pair
jjones@adm.com test123


kim@cust.com test123

标签: javahashmapnotepad

解决方案


要将Properties对象转换为 a HashMap<String, String>,请复制所有条目:

HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
    hmp.put(name, prop.getProperty(name));

如果属性文件可以包含其他属性,则在复制时进行过滤,例如

HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
    if (name.endsWith("_User") || name.endsWith("_Psd"))
        hmp.put(name, prop.getProperty(name));

或使用正则表达式相同:

Pattern suffix = Pattern.compile("_(User|Psd)$");
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
    if (suffix.matcher(name).find())
        hmp.put(name, prop.getProperty(name));

推荐阅读