-2

I have a HashMap which contains Set<String> as Key and Value,

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

If I want to write this HashMap object into a file, Whats is the best way to do it. Also I want to read this back from that file as HashMap<Set<String>, Set<String>>.

Justin
  • 735
  • 1
  • 15
  • 32

2 Answers2

1

Here is how I write a map to file and read it back from the file. You can adapt it for your usecase.

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");
}
awsome
  • 2,143
  • 2
  • 23
  • 41
0

I am not sure, if you really want to do this but using serialization it is as simple like that:

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(yourFile)))
{
   out.writeObject(map);
}
M.F
  • 403
  • 2
  • 10