Thursday, 19 October 2017

Example of Serialization/Deserialization

package com.test.yuvagen.basic;

/**
 * Implements Serializable
 *
 * @author:http://javainterviewprograms.blogspot.in/
 *
 */
import java.io.*;

class Demo implements Serializable
{
    public int a;
    public String b;
         
    // Default constructor
    public Demo(int a, String b)
    {
        this.a = a;
        this.b = b;
    }

}

class Test
{
    public static void main(String[] args)
    {  
        Demo object = new Demo(1, "saurabh");
        String filename = "file.ser";
        
        // Serialization
        try
        {  
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);
            
            // Method for serialization of object
            out.writeObject(object);
            
            out.close();
            file.close();
            
            System.out.println("Object has been serialized");

        }
        
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }


        Demo object1 = null;

        // Deserialization
        try
        {  
            // Reading the object from a file
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);
            
            // Method for deserialization of object
            object1 = (Demo)in.readObject();
            
            in.close();
            file.close();
            
            System.out.println("Object has been deserialized ");
            System.out.println("a = " + object1.a);
            System.out.println("b = " + object1.b);
        }
        
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }
        
        catch(ClassNotFoundException ex)
        {
            System.out.println("ClassNotFoundException is caught");
        }

    }
}

Output :
Object has been serialized
Object has been deserialized
a = 1

b = saurabh

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...