首页 > 解决方案 > 序列化 HashMap 并写入文件

问题描述

我有一个HashMap包含Set<String>键和值的,

HashMap<Set<String>, Set<String>> mapData = new HashMap<Set<String>, Set<String>>();

如果我想将此HashMap对象写入文件,Whats 是最好的方法。我也想从那个文件中读回HashMap<Set<String>, Set<String>>.

标签: javahashmapfile-writing

解决方案


这是我将映射写入文件并从文件中读回的方法。您可以根据您的用例对其进行调整。

public static Map<String, Integer> deSerializeHashMap() throws ClassNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("/opt/hashmap.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Map<String, Integer> map = (Map<String, Integer>) ois.readObject();
    ois.close();
    System.out.printf("De Serialized HashMap data  saved in hashmap.ser");
    return map;
}

public static void serializeHashMap(Map<String, Integer> hmap) throws IOException {
    FileOutputStream fos = new FileOutputStream("/opt/hashmap.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(hmap);
    oos.close();
    fos.close();
    System.out.printf("Serialized HashMap data is saved in hashmap.ser");
}

推荐阅读