使用属性文件中的条目填充HashMap [英] Populating a HashMap with entries from a properties file
问题描述
我想使用 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.
前面的方法:
Earlier approach:
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 ?
推荐答案
如果我理解正确,属性中的每个值都是表示Integer的String。所以代码如下所示:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!