Java ObjectInputStream .defaultReadObject ()

Syntax

ObjectInputStream.defaultReadObject() has the following syntax.

public void defaultReadObject()   throws IOException ,    ClassNotFoundException

Example

In the following code shows how to use ObjectInputStream.defaultReadObject() method.


//  w  w w .  j  ava  2 s.c  om

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {

  public static void main(String[] args) throws Exception {

    FileOutputStream out = new FileOutputStream("test.txt");
    ObjectOutputStream oout = new ObjectOutputStream(out);

    oout.writeObject(new Example());
    oout.flush();
    oout.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        "test.txt"));

    Example a = (Example) ois.readObject();

    System.out.println(a.s);
    ois.close();
  }

}

class Example implements Serializable {

  String s = "Hello World from java2s.com!";

  private void readObject(ObjectInputStream in) throws IOException,
      ClassNotFoundException {
    in.defaultReadObject();

  }
}

The code above generates the following result.