Tuesday 22 November 2016

Serialization and Deserialization in Java

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
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.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.


Address.java
import java.io.Serializable;  
class Address implements Serializable
{  
String addressLine,city,state;  
public Address(String addressLine, String city, String state)
 {  
  this.addressLine=addressLine;  
  this.city=city;  
  this.state=state;  
 }  
}  
Student.java
import java.io.Serializable;  
class Student implements Serializable
{  
 int id;  
 String name;  
 Address address; // aggregation
 public Student(int id, String name) 
 {  
  this.id = id;  
  this.name = name;  
 } 
}  

SerializaionTestWithAggregation.java
import java.io.*;  
class SerializaionTestWithAggregation
{  
public static void main(String args[])throws Exception
 {  
  Student s1 = new Student(1,"Sivasankar");  
  Address a1 = new Address("40-R, "Fremont","California ");  
  FileOutputStream fout=new FileOutputStream("serial.txt");  
  ObjectOutputStream out=new ObjectOutputStream(fout);  
  out.writeObject(s1);  
   out.writeObject(a1);   // Remove and run Deserialize u will get EOF
  out.flush();  
  System.out.println("success"); 
 }  
}  

Deserialize.java

import java.io.*; 

class Deserialize
{  
 public static void main(String args[])throws Exception
 {  
    
  ObjectInputStream in=new ObjectInputStream(new FileInputStream("serial.txt"));  
  
  Student s=(Student)in.readObject();  
    Address a =(Address)in.readObject();  
  
  System.out.println(s.id+" "+s.name+" "+a.addressLine+" "+ a.city+" "+a.state);  
  
  in.close();  
 }  

}  

Output:
Run Serialize.java



Run Deserialize.java



No comments:

Post a Comment