Tuesday, November 12

Java Serialization and Deserialization

Introduction: Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.The reverse process of creating object from binary stream is called deserialization. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Serialization classes:

OutputStream : we’ll use FileOutputStream to write data to a file.
ObjectOutputStream : writes primitive data types and graphs of Java objects to an OutputStream.
 WriteObject() Method : it writes an object to the stream.

Deserialization classes:

InputStream : We’ll use FileInputStream as source stream.
ObjectInputStream: It reads from inputStream.
ReadObject() Method:  It reads raw bytes and convert to an object.

In this sample I’ll use a person class and an address class. The person class holds the reference of an address class. We will serialize the data and store it in c:\ project\ folder as tst.ser file. To deserialize the data we will create an instance of FileInputStream class that takes this tst.ser file as source.

Code:

import java.io.Serializable;

public class person implements Serializable {

            String fname;
            String lname;
            int age;
            address addr; //reference class
           
            public person()
            {}
           
            public person(String fn,String ln,int age,address a)
            {
                        this.fname=fn;
                        this.lname=ln;
                        this.age=age;
                        this.addr=a;
            }
           
            public String getFName() {return fname;}
            public String getLName() {return lname;}
            public int getAge() {return age;}
            public address getAddress() { return addr;}
           
            public String setFName(String fn) { return fname=fn;}
            public String setLName(String ln) { return lname=ln;}
            public int setAge(int a) { return age=a;}
            public address setAddress(address adr){return addr=adr;}
           
}
import java.io.Serializable;

public class address implements Serializable{
           
            String str;
            String city;
            String state;
            String zip;
           
            public address(){};
            public address(String a,String c,String s,String z)
            {
                        super();
                        this.str=a;this.city=c;this.state=s;this.zip=z;
            }
   
            public String getStreet(){return str;}
            public String getCity() {return city;}
            public String getState() {return state;}
            public String getZip(){return zip;}
           
            public String setStr(String st){return str=st;}
            public String setCity(String ct){return city=ct;}
            public String setSttae(String st){return state=st;}
            public String setZip(String zp){return zip=zp;}
           
           
}
import java.io.*;

public class serializeDeserailize {
           
            public static void main(String[] args)
            {
                        //create a person instance
                        person p=new person();
                        p.setFName("Adam");
                        p.setLName("Smith");
                        p.setAge(20);
                        //create an address instance
                        address a=new address();
                        a.setStr("Lake Shore Drive");
                        a.setCity("Chicago");
                a.setSttae("IL");
                        a.setZip("65987");
                        p.setAddress(a);
                       
           
                        //Serialize person object
                        try {
                                    FileOutputStream fos=new FileOutputStream("c:/project/tst.ser");
                                    ObjectOutputStream obj=new ObjectOutputStream (fos);
                                    obj.writeObject(p);
                                    obj.close();
                                    fos.close();
                                   
                                   
                           }catch (Exception e)
                        {
                                    e.printStackTrace();
                        }
                       
                        // Deserialize
                       
                        p=null;
                        try {
                                   
                                    InputStream fin=new FileInputStream("c:/project/tst.ser");
                                    ObjectInputStream in=new ObjectInputStream(fin);
                                    p=(person) in.readObject(); //cast to person object
                                    in.close();
                                    fin.close();
                       
                        }catch (Exception ex)
                        {
                                    ex.printStackTrace();
                        }
                       
                        System.out.println("After Deserialization:" );
                        System.out.println("First Name:" + p.getFName());
                        System.out.println("Last Name:" + p.getLName());
                        System.out.println(("Age:" + p.getAge()));
                        System.out.println("Address:" + p.getAddress().getStreet() + " " +  p.getAddress().getCity() + "," +  p.getAddress().getState() + "-" +  p.getAddress().getZip());
                       
            }

            }

Output:
First Name:Adam
Last Name:Smith
Age:20

Address:Lake Shore Drive Chicago,IL-65987

No comments:

Post a Comment