Tuesday, August 30, 2011

Serialization and Deserialization in java


//serializableClass.java

import java.io.Serializable;

public class serializableClass implements Serializable
{
/**
* Default serial version UID
*/
private static final long serialVersionUID = 1L;
String s;
int age;

public serializableClass(String s,int age)
{
this.s = s;
this.age = age;
}
public String toString()
{
return s+" is "+age+" year old.";
}
}



//serializationExample.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class serializationExample
{
public static void main(String args[])
{
//Serialization
try
{
serializableClass object1 = new serializableClass("Arun",26);
System.out.println("Object 1 :"+object1);

FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
//Deserialization
try
{
serializableClass object2;

FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (serializableClass)ois.readObject();

System.out.println("Object 2 :"+object2);
ois.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}


Output =>
Object 1 :Arun is 26 year old.
Object 2 :Arun is 26 year old.

No comments:

Post a Comment