Topics Index

Input/Output: Exploring > Serialization >
Siva Nookala - 14 Apr 2016
ObjectInputStream is used to restore the objects which are written to a OutputStream by ObjectOutputStream

Only objects that support the or interface can be read from streams. The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type.
FileInputStream fis = new FileInputStream("t.tmp");
      ObjectInputStream ois = new ObjectInputStream(fis);

      int i = ois.readInt();
      String today = (String) ois.readObject();
      Date date = (Date) ois.readObject();

Implementing the Serialization In Java interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects, saving and restoring entire graphs. Serialization In Java classes that require special handling during the serialization and deserialization process should implement the following methods:
private void writeObject( stream)
     throws IOException;

private void readObject( stream)
     throws IOException, ClassNotFoundException;

private void readObjectNoData()
     throws ObjectStreamException;

The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method.

public class OriginalClass implements Serializable
    public String someName;
    OriginalClass(String name)
        this.someName = name;
    public String toString()
        return someName;

public class ReadingData
    public void readData(String file)
        ObjectInputStream ois = null;
            ois = new ObjectInputStream(new FileInputStream(file));
            Object o = null;
            while((o = ois.readObject()) != null) //reading objects from file
                if(o instanceof OriginalClass)
                    System.out.println(((OriginalClass) o).toString());
        catch(EOFException ex)
            System.out.println("End of file");
        catch(FileNotFoundException ex)
            System.out.println("File not found");
        catch(IOException ex)
            System.out.println("Io exception occured");
        catch(ClassNotFoundException e)
            // TODO Auto-generated catch block

    public static void main(String[] args)
        new ReadingData().readData("somefile.txt");
Output :
End of file

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.