Populating a HashMap with entries from a properties file(使用属性文件中的条目填充 HashMap)
问题描述
我想使用 Properties
类填充 HashMap
.
我想加载 .propeties
文件中的条目,然后将其复制到 HashMap
.
I want to populate a HashMap
using the Properties
class.
I want to load the entries in the .propeties
file and then copy it into the HashMap
.
之前,我只是用属性文件初始化HashMap
,但现在我已经定义了HashMap
,只想在构造函数中初始化它.
Earlier, I used to just initialize the HashMap
with the properties file, but now I have already defined the HashMap
and want to initialize it in the constructor only.
较早的方法:
Properties properties = new Properties();
try {
properties.load(ClassName.class.getResourceAsStream("resume.properties"));
} catch (Exception e) {
}
HashMap<String, String> mymap= new HashMap<String, String>((Map) properties);
但现在,我有这个
public class ClassName {
HashMap<String,Integer> mymap = new HashMap<String, Integer>();
public ClassName(){
Properties properties = new Properties();
try {
properties.load(ClassName.class.getResourceAsStream("resume.properties"));
} catch (Exception e) {
}
mymap = properties;
//The above line gives error
}
}
如何在此处将属性对象分配给 HashMap
?
How do I assign the properties object to a HashMap
here?
推荐答案
如果我理解正确的话,属性中的每个值都是一个代表整数的字符串.所以代码看起来像这样:
If I understand correctly, each value in the properties is a String which represents an Integer. So the code would look like this:
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
mymap.put(key, Integer.valueOf(value));
}
这篇关于使用属性文件中的条目填充 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用属性文件中的条目填充 HashMap


基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01