记事本到HashMap-Java



我编写了一个小程序,该程序根据提供的用户类型Admin/客户从文本文件中读取,并打印单个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 中。所以我删除了用户类型参数

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

我得到空空作为输出。我想不出在HashMap中获取它们的方法,我可以使用一些提示/帮助。

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

kim@cust.com test123

要将Properties对象转换为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));

最新更新