Serialization - Java

 This is the process of writing the state of an object to stream.This is useful when you want to save the state of your program to a presistant storage area such as a file. At a later time you may restore these objects by using the process of deserialisation.

            Only an object that implements the serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members . it is simply used to indicate that a class may be serialized.

WRITE A PROGRAM ON SERIALIZATION.

import java.io.*;
class Abc implements Serializable
{
int i;
String n;
double d;
public Abc(String s,int x,double d)
{
n=s;
i=x;
this.d=d;
}
public String toString()
{
return(i+" "+n+" "+d);
}
}

class Sample
{
public static void main(String args[])
{
try
{
Abc ob1=new Abc("vision",20,2.56);
FileOutputStream fout=new FileOutputStream("file");
System.out.println(ob1);
ObjectOutputStream oos=new ObjectOutputStream(fout);
oos.writeObject(ob1);
oos.flush();
oos.close();
}
catch(Exception e)
{
System.out.println("Exception during srialization: "+e);
System.exit(0);
}
try
{
Abc ob2;
FileInputStream fin=new FileInputStream("file");
ObjectInputStream oi=new ObjectInputStream(fin);
ob2=(Abc)oi.readObject();
oi.close();
System.out.println("Object2: "+ob2);
}
catch(Exception e)
{
System.out.println("Exception during desrialization: "+e);
System.exit(0);
}
}
}

 

For
Online Classes

Contact Us: 9885348743