javahashmapfile-writing

Serializing HashMap And writing Into a file


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>>.


Solution

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