Retrieving serialized objects from file
by, 11-10-2011 at 05:35 PM (1520 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.
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.Java Code:FileInputStream f_in = new FileInputStream("C:\myvector.data"); ObjectInputStream obj_in = new ObjectInputStream (f_in); Vector v = (Vector)obj_in.readObject();