Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream. : ObjectInputStream « File « Java Tutorial






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

class MyClass implements Serializable {
  String str;
  double[] vals;
  File fn;

  public MyClass(String s, double[] nums, String fname) {
    str = s;
    vals = nums;
    fn = new File(fname);
  }

  public String toString() {
    String data = "  str: " + str + "\n  vals: ";

    for (double d : vals)
      data += d + " ";
    data += "\n  fn: " + fn.getName();

    return data;
  }
}

public class Main {
  public static void main(String[] argv) throws Exception {
    double v[] = { 1.1, 2.2, 3.3 };
    double v2[] = { 9.0, 8.0, 7.7 };

    MyClass obj1 = new MyClass("This is a test", v, "Test.txt");
    MyClass obj2 = new MyClass("Alpha Beta Gamma", v2, "Sample.dat");

    ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream("obj.dat"));
    System.out.println("obj1:\n" + obj1);
    fout.writeObject(obj1);
    System.out.println("obj2:\n" + obj2);
    fout.writeObject(obj2);
    fout.close();

    ObjectInputStream fin = new ObjectInputStream(new FileInputStream("obj.dat"));
    MyClass inputObj;

    inputObj = (MyClass) fin.readObject();
    System.out.println("First object:\n" + inputObj);

    inputObj = (MyClass) fin.readObject();
    System.out.println("Second object:\n" + inputObj);
    fin.close();
  }
}








11.22.ObjectInputStream
11.22.1.Create ObjectInputStream from FileInputStream
11.22.2.Reading objects from file using ObjectInputStream
11.22.3.Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
11.22.4.Store objects in file