View RSS Feed

My Java Tips

Retrieving serialized objects from file

Rate this Entry
by , 11-10-2011 at 04:35 PM (1074 Views)
I assume that you are aware of how to serialize objects and save them into files on the disk. Now I will talk about how to retrieve serialized objects.


You have to use FileInputStream and ObjectInputStream to fetch the object. Specify the file which contains the object in FileInputStream. Once ObjectInputStrem is initialized, just use in.readObject method of ObjectInputStream to fetch the object.

In the following example, I am fetching a Vector from a file on disk.

Java Code:
FileInputStream f_in = new FileInputStream("C:\myvector.data");
ObjectInputStream obj_in = new ObjectInputStream (f_in);
Vector v = (Vector)obj_in.readObject();
If file doesn’t exist, java.io.FileNotFoundException will be thrown. We can store and fetch objects of our own classes if they implement Serializable interface. If you want to store multiple objects in same file, you can put them in a Vector and write to a file. Vector class also implement Serializable interface. So can can get vector object back in the same way as shown above.

Submit "Retrieving serialized objects from file" to Facebook Submit "Retrieving serialized objects from file" to Digg Submit "Retrieving serialized objects from file" to del.icio.us Submit "Retrieving serialized objects from file" to StumbleUpon Submit "Retrieving serialized objects from file" to Google

Comments