使用存储在.properties文件中的所有条目填充HashMap

时间:2013-05-02 20:13:27

标签: java properties hashmap

如何使用存储在单独HashMap文件中的所有条目填充.properties? 我在Eclipse的bin文件夹中放置了一个文件resume.propertiesclass文件。

该文件包含此类条目

available = 1
bismarck = 1
employees = 1
reports = 1
home = 1
company = 1
work = 2
........

我想在调用该类的构造函数后立即将这些条目填充到我的HashMap中。

public class TextClassifier {

  static HashMap<String,Integer> resume = new HashMap<String, Integer>();

  public TextClassifier(){
    try {
      properties.load(TextClassifier.class.getResourceAsStream("resume.properties"));              
    }
    catch (Exception e) {}

    for (String key : properties.stringPropertyNames()) {
      String value = properties.getProperty(key);
      resume.put(key, Integer.valueOf(value));
    }

  }

  public static void printHashmap(HashMap<String,Integer> map){
    for(Map.Entry<String, Integer> entry:map.entrySet()){
      int val=entry.getValue();
      String key=entry.getKey();
      System.out.println(key + " = " + val);
    }
  }

  public static void main(String args[]){
    new TextClassifier();
    TextClassifier.printHashmap(TextClassifier.resume);

  }
}

但是当我使用printAll方法打印条目并将它们与actaul文件中的条目匹配时,我发现它们不匹配。这些是打印的条目,文件中没有!!

我很多HashMaps(我还没有展示),所以其他文件中的条目可能会打印出来。错误在哪里?

1 个答案:

答案 0 :(得分:1)

您正在将一个不同的resume.properties文件加载到您认为正在游荡的文件中。

检查名为resume.properties的其他文件的资源路径以确定它。

您也可以直接从文件加载,以使用绝对路径强制使用特定文件:

properties.load(new FileInputStream("/some/path/resume.properties");

另一种可能性是properties是一个在其他地方使用的静态变量,并且由于load()方法不能清除现有值 - 它只是添加属性 - 您看到之前加载的值价值在其他地方。

相关问题