java - 记事本到 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
解决方案
要将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));
推荐阅读
- dhis-2 - 在您的网站上直接嵌入实时 dhis2 数据
- java - 从 LocalDateTime Java 8 获取 UTC java.uti.Date
- java - 如何模拟构造函数一个静态公共类以引发异常
- python - Padas,如何创建列是多维数组的数据集?
- angular - When creating a dynamic checkbox list i can't receive data from service (observable)
- pandas - 填充熊猫数据框
- http - 托管没有端口转发的服务器
- java - 如何修复此功能它总是返回 false
- python - Python 2.7:setlogmask(0) 不禁用系统日志
- javascript - 什么事件会触发点击释放-Javascript/Reactjs