Wednesday, March 11, 2009

Customized Serialization



package myio;

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



class Dog2 implements Serializable
{
transient Cat1 c=new Cat1();
private void writeObject(ObjectOutputStream os)throws Exception
{
os.defaultWriteObject();
int i=c.j;
os.writeInt(i);
}
private void readObject(ObjectInputStream is)throws Exception
{
is.defaultReadObject();
int i=is.readInt();
c=new Cat1();
c.j=i;
}
}
class Cat1
{
int j=20;
}
public class SerDemo3
{
public static void main(String arg[])throws Exception
{
Dog2 d=new Dog2();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog2 d1=(Dog2)ois.readObject();
System.out.println(d1.c.j);
}
}

output:
20





0 comments:

Post a Comment