Java IO Tutorial - Java Externalizable .readExternal (ObjectInput in)








Syntax

Externalizable.readExternal(ObjectInput in) has the following syntax.

void readExternal(ObjectInput in)   throws IOException ,    ClassNotFoundException

Example

In the following code shows how to use Externalizable.readExternal(ObjectInput in) method.

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
/*from ww w . j  a v  a2  s . c om*/
class A implements Externalizable {
  public A() {
    System.out.println("A Constructor");
  }

  public void writeExternal(ObjectOutput out) throws IOException {
    System.out.println("A.writeExternal");
  }

  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    System.out.println("A.readExternal");
  }
}

class B implements Externalizable {
  B() {
    System.out.println("B Constructor");
  }

  public void writeExternal(ObjectOutput out) throws IOException {
    System.out.println("B.writeExternal");
  }

  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    System.out.println("B.readExternal");
  }
}

public class Main {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    A b1 = new A();
    B b2 = new B();
    ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("File.out"));
    o.writeObject(b1);
    o.writeObject(b2);
    o.close();

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("File.out"));
    b1 = (A) in.readObject();
  }
}

The code above generates the following result.