Reconstructing an externalizable object : 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;

public class MainClass {

  public static void main(String[] args) throws IOException, ClassNotFoundException {
    System.out.println("Constructing objects:");
    MyBean myBean = new MyBean("A String ", 47);
    System.out.println(myBean);
    ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("MyBean.out"));
    System.out.println("Saving object:");
    o.writeObject(myBean);
    o.close();


    ObjectInputStream in = new ObjectInputStream(new FileInputStream("MyBean.out"));
    System.out.println("Recovering:");
    myBean = (MyBean) in.readObject();
    System.out.println(myBean);
  }
}

class MyBean implements Externalizable {
  private int i;

  private String s; // No initialization

  public MyBean() {
    System.out.println("MyBean Constructor");
    // s, i not initialized
  }

  public MyBean(String x, int a) {
    System.out.println("MyBean(String x, int a)");
    s = x;
    i = a;
    // s & i initialized only in nondefault constructor.
  }

  public String toString() {
    return s + i;
  }

  public void writeExternal(ObjectOutput out) throws IOException {
    System.out.println("MyBean.writeExternal");
    out.writeObject(s);
    out.writeInt(i);
  }

  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    System.out.println("MyBean.readExternal");
    s = (String) in.readObject();
    i = in.readInt();
  }

}

/**/
Constructing objects:
MyBean(String x, int a)
A String 47
Saving object:
MyBean.writeExternal
Recovering:
MyBean Constructor
MyBean.readExternal
A String 47








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