ObjectInputStream — Reading Object From a File

This example will show you how to read a Java object from a file using ObjectInputStream. This is a part of serialization topic.
import java.io.*;
class ReadObj
{
    public static void main(String args[]) throws Exception
    {
        FileInputStream fin=new FileInputStream("obj.dat");
       
        ObjectInputStream oin=new ObjectInputStream(fin);
       
        String st=(String)oin.readObject();
       
        System.out.println(st);
    }
}

Here, the file obj.dat contains a String object in it. You need to note that to read an object from a file, you need to write it to that file first. The previous program will show you how to write an object to a file.

fin=new FileInputStream("obj.dat"): This statement creates a FileInputStream object pointing to obj.dat
oin=new ObjectInputStream(fin): This statement creates an ObjectInputStream object pointing to FileInputStream object fin.
oin.readObject(): This method in ObjectInputStream class reads an object from the file obj.dat and returns it. As this method returns java.lang.Object, type casting is necessary.

No comments: