Serialization

Serialization concept allows object of class to be written on disk. Class which implements serializable interface, object of that class can be saved in a file. Under serialiazation object can be represented as sequence of bytes.Class which need to be serializable must implements serialazable interface. For saving object of class objectOutputStream need to be created.

Program:Writing Object to file


	import java.io.*;
class employee implements Serializable
{
String name;
int salary;
String position;
employee ()
{
name=null;
salary=0;
position=null;
}
employee(String n,int s, String p)
{
name=n;
salary=s;
position=p;
}
void show()
{
System.out.println("Name:"+name);
System.out.println("Salary:"+salary);
System.out.println("Position:"+position);
}
}
class tw
{
public static void main(String arg[]) throws IOException
{
employee e1=new employee("rajesh",120000,"manager");
FileOutputStream fos=new FileOutputStream("one.txt");
ObjectOutputStream os=new ObjectOutputStream(fos);
os.writeObject(e1);
}
}

Reading object from file

Reading from object also known as deserializing of object.


import java.io.*;
class two
{
public static void main(String arg[]) throws Exception
{
employee e1;
FileInputStream fos=new FileInputStream("one.txt");
ObjectInputStream os=new ObjectInputStream(fos);
e1=(employee)os.readObject();
e1.show();
}
}