Simple use of Externalizable : Externalizable « File « Java Tutorial






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;

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 MainClass {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    System.out.println("Constructing objects:");
    A b1 = new A();
    B b2 = new B();
    ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("File.out"));
    System.out.println("Saving objects:");
    o.writeObject(b1);
    o.writeObject(b2);
    o.close();

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("File.out"));
    System.out.println("Recovering b1:");
    b1 = (A) in.readObject();
  }
}
/*
*/
Constructing objects:
A Constructor
B Constructor
Saving objects:
A.writeExternal
B.writeExternal
Recovering b1:
A Constructor
A.readExternal








11.39.Externalizable
11.39.1.Simple use of Externalizable
11.39.2.implements Externalizable
11.39.3.Reconstructing an externalizable object