SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
/* this uses one object(miao) for serialization
and another object (miao2) for deserialization
Plus we will try to save value of Animal's member: age*/
import java.io.*;
//Non serializable Class
class Animal
{
int age;
}
//Serializable Class
class PetAnimal extends Animal implements Serializable
{
int tailSize;
String name;
PetAnimal(int age, int tailSize, String name)
{ this.age=age;
this.tailSize=tailSize;
this.name=name;
}
//My method for serialization
private void writeObject(ObjectOutputStream os)
{
try
{
os.defaultWriteObject();
System.out.println("defaultWrite successful");
os.writeInt(age);
System.out.println("writeInt successful");
os.close();
}
catch (Exception e)
{
System.out.println("Exception in writeObject");
e.printStackTrace();
}
}
//My method for de-serialization
private void readObject(ObjectInputStream ois)
{
try
{
ois.defaultReadObject();
age= ois.readInt();
ois.close();
}
catch (Exception e)
{
System.out.println("Exception in readObject");
e.printStackTrace();
}
}
}
//Class that serializes
class MyHouse4
{
public static void main(String[] args){
PetAnimal miao=new PetAnimal(1, 2,"cat");
System.out.println("Before Serialization: " + miao.age+" "+miao.tailSize+" "+miao.name);
try{
FileOutputStream fs=new FileOutputStream("PetAnimal.ser");
System.out.println("File is fine");
ObjectOutputStream os= new ObjectOutputStream(fs);
System.out.println("object stream created is fine");
os.writeObject(miao);
System.out.println("object serialized");
os.close();
}
catch (Exception e)
{
System.out.println("Exception in serializing");
e.printStackTrace();
}
//Now deserialize
NewHouse house= new NewHouse();
house.deSerialize();
}
}
//Class that deserializes
class NewHouse
{
PetAnimal miao2=null;
void deSerialize()
{
try{
FileInputStream fis=new FileInputStream("PetAnimal.ser");
ObjectInputStream ois= new ObjectInputStream(fis);
miao2 = (PetAnimal) ois.readObject();
ois.close();
}
catch (Exception e)
{
System.out.println("Exception in de-serializing");
e.printStackTrace();
}
System.out.println("After de-serialization: " + miao2.age+" "+miao2.tailSize+" "+miao2.name);
}
}
SCJP 5.0 -- 97%