Saturday, 29 July 2017

Serialization and Deserialization Examaple (convert HashMap to encoded txt file and read that file to HashMap)

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class SerializationTest {

/**
* HashMap converted .txt file and .txt file to HashMap
*/
public static void main(String[] args) {

HashMap mainMap=new HashMap<String,HashMap>();  //main hashmap

HashMap mainMap1=new HashMap<String,HashMap>();
 
HashMap<String, String> childMap=new HashMap<String,String>();
  childMap.put("DocName", "DocumentName");
  childMap.put("Language", "English");
  childMap.put("Status", "Success");
  childMap.put("Location", "D:/dhsgds/hjasdhjgs");
  childMap.put("Path", "D:/dhsgds/hjasdhjgs");

 mainMap.put("docID1", childMap);
 mainMap.put("docID2", childMap);

 try
          {
                 FileOutputStream fos =
                    new FileOutputStream("F:/Education/test.txt");
//The above hashmap converted to text file in that direcotry with encoded format
                 ObjectOutputStream oos = new ObjectOutputStream(fos);
                 oos.writeObject(mainMap);
                 oos.close();
                 fos.close();
                 System.out.printf("Serialized HashMap data is saved in hashmap.ser");
          }catch(IOException ioe)
           {
                 ioe.printStackTrace();
           }
 try
     {
 System.out.println("enter try for read");
        FileInputStream fis = new FileInputStream("F:/Education/test.txt");

        ObjectInputStream ois = new ObjectInputStream(fis);
        mainMap1 = (HashMap) ois.readObject();
        ois.close();
        fis.close();
     }catch(IOException ioe)
     {
        ioe.printStackTrace();
        return;
     }catch(ClassNotFoundException c)
     {
        System.out.println("Class not found");
        c.printStackTrace();
        return;
     }
     System.out.println("Deserialized HashMap..");
     // Display content using Iterator
     Set set = mainMap1.entrySet();
     Iterator iterator = set.iterator();
     while(iterator.hasNext()) {
        Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("key: "+ mentry.getKey() + " & Value: ");
        System.out.println(mentry.getValue());
     }
}

}