我想使用Properties
类填充HashMap
。我想加载.propeties
文件中的条目,然后将其复制到HashMap
。使用属性文件中的条目填充HashMap
此前,我曾用属性文件初始化HashMap
,但现在我已经定义了HashMap
并且只想在构造函数中初始化它。
此前的做法:
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
?
如果你使用的getResourceAsStream当越来越**空* *,这可能是因为你正在寻找类路径之外的文件。因此,要读取绝对文件路径,您可以执行:\t \t'File file = new File(“absolute/file/path/resume.properties”); \t \t \t FileInputStream fileInputStream = new FileInputStream(file); \t \t \t properties.load(fileInputStream); \t \t \t fileInputStream.close();' – 2015-01-12 09:40:31