使用属性文件中的条目填充HashMap

One*_*ror 18 java hashmap

我想填充一个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);
Run Code Online (Sandbox Code Playgroud)

但现在,我有这个

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
}
}
Run Code Online (Sandbox Code Playgroud)

如何将属性对象分配给HashMap此处?

JB *_*zet 26

如果我理解正确,属性中的每个值都是一个表示整数的String.所以代码看起来像这样:

for (String key : properties.stringPropertyNames()) {
    String value = properties.getProperty(key);
    mymap.put(key, Integer.valueOf(value));
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你在使用getResourceAsStream**时得到**null,可能是因为你在classpath之外寻找文件.所以要读取绝对文件路径,你可以这样做:`File file = new File("absolute/file/path/resume.properties"); FileInputStream fileInputStream = new FileInputStream(file); properties.load(的FileInputStream); fileInputStream.close();` (3认同)

cah*_*hen 22

使用 .entrySet()

for (Entry<Object, Object> entry : properties.entrySet()) {
    map.put((String) entry.getKey(), (String) entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)


apr*_*dan 8

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())));
Run Code Online (Sandbox Code Playgroud)