我想填充一个HashMap
使用Properties
类。
我要加载的项.propeties
文件,然后将其复制到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
吗?
如果正确地明白,在属性的每个值是代表一个整数的字符串。 因此,代码是这样的:
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
mymap.put(key, Integer.valueOf(value));
}
使用.entrySet()
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
Java的8风格:
Properties properties = new Properties();
// add some properties here
Map<String, String> map = new HashMap();
map.putAll(properties.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString())));
public static Map<String,String> getProperty()
{
Properties prop = new Properties();
Map<String,String>map = new HashMap<String,String>();
try
{
FileInputStream inputStream = new FileInputStream(Constants.PROPERTIESPATH);
prop.load(inputStream);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Some issue finding or loading file....!!! " + e.getMessage());
}
for (final Entry<Object, Object> entry : prop.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
return map;
}