Friday, March 20, 2009

Simple java program to deserialize an Object from a flat file

First go through the above article to serialize an object to a flat file

Now below code is to retrieve the object from the flat file.

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class readSer {
public readSer() {
}
public static void main(String[] args) {
readSer readSer = new readSer();
try{
FileInputStream fs = new FileInputStream("C:\\my.ser");
ObjectInputStream os = new ObjectInputStream(fs);
testJava a = (testJava)os.readObject(); <-- Type Casting is important
System.out.println("Length From Serialized Object: "+ a.getLength());
System.out.println("Width From Serialized Object: "+ a.getWidth());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output
Length From Serialized Object: 5
Width From Serialized Object: 4

No comments: