What is Deserialization in Java?



After a serialized object has been written into a file, it can be read from the file and Deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Example

import java.io.*;

public class DeserializeDemo {
   public static void main(String [] args) {
      Employee e = null;

      try {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      } catch (IOException i) {
         i.printStackTrace(); return;
      } catch (ClassNotFoundException c) {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
   }
}

Output

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Monica Mona
Monica Mona

Student of life, and a lifelong learner


Advertisements