Aug 12, 2011

Serialization and deSerialzation examples

 // save it as student.java

import java.io.*;
class student implements Serializable
{
int a;
float b;
student(int a,float b)
{
this.a=a;
this.b=b;
}
public String toString()
{
return "a="+a+"b="+b;
}
}
















// save it as writeObject.java

import java.io.*;

class WriteObject
{
public static void main(String ...arg)
{
ObjectOutputStream oos=null;
FileOutputStream fis=null;
try
{
fis=new FileOutputStream("abc.txt");
oos=new ObjectOutputStream(fis);

student st=new student(10,20);
oos.writeObject(st);
}
catch(IOException ie)
{
ie.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
oos.close();
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}





Deserialzation


//ReadObject.java



import java.io.*;

class ReadObject
{
public static void main(String ...arg)
{
ObjectInputStream ois=null;
FileInputStream fis=null;
try
{
fis=new FileInputStream("abc.txt");
ois=new ObjectInputStream(fis);

Object o=ois.readObject();
student s=(student)o;
System.out.println(s.toString());



}
catch(IOException ie)
{
ie.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
ois.close();
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}