序列化 HashMap 并写入文件

Serializing HashMap And writing Into a file

我有一个 HashMap,其中包含 Set<String> 作为键和值,

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

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

我不确定,如果你真的想这样做但使用序列化就这么简单:

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(yourFile)))
{
   out.writeObject(map);
}

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

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");
}