Class combination Serialization : Object Serialization « File « Java Tutorial






import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

class ID implements Serializable {
}

class Employee implements Serializable {
  private String name;

  private ID myID;

  Employee(String nm, ID h) {
    name = nm;
    myID = h;
  }

  public String toString() {
    return name + "[" + super.toString() + "], " + myID + "\n";
  }
}

public class MainClass {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    ID id = new ID();
    List employees = new ArrayList();
    employees.add(new Employee("A", id));
    employees.add(new Employee("B", id));
    employees.add(new Employee("C", id));
    System.out.println("employees: " + employees);
    ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
    ObjectOutputStream o1 = new ObjectOutputStream(buf1);
    o1.writeObject(employees);
    o1.writeObject(employees); 

    ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
    ObjectOutputStream o2 = new ObjectOutputStream(buf2);
    o2.writeObject(employees);

    ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
    ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
    List emp1 = (List) in1.readObject(), emp2 = (List) in1.readObject(), emp3 = (List) in2
        .readObject();
    System.out.println("emp1: " + emp1);
    System.out.println("emp2: " + emp2);
    System.out.println("emp3: " + emp3);
  }
}

/*
*/
employees: [A[Employee@126b249], ID@182f0db
, B[Employee@192d342], ID@182f0db
, C[Employee@6b97fd], ID@182f0db
]
emp1: [A[Employee@750159], ID@1abab88
, B[Employee@18a7efd], ID@1abab88
, C[Employee@1971afc], ID@1abab88
]
emp2: [A[Employee@750159], ID@1abab88
, B[Employee@18a7efd], ID@1abab88
, C[Employee@1971afc], ID@1abab88
]
emp3: [A[Employee@16cd7d5], ID@cdedfd
, B[Employee@1c39a2d], ID@cdedfd
, C[Employee@bf2d5e], ID@cdedfd
]








11.38.Object Serialization
11.38.1.Conditions for Serialization
11.38.2.Storing Objects in a File
11.38.3.Reading an Object From a File
11.38.4.Serializing Variations on an Object
11.38.5.Writing objects sequentially to a file with class ObjectOutputStream
11.38.6.Read a file of objects sequentially and displays each record
11.38.7.Only parent class is Serializable
11.38.8.Saving and restoring the state of classes
11.38.9.Class combination Serialization
11.38.10.Controlling serialization by adding your own
11.38.11.Serialization with ObjectInputStream and ObjectOutputStream
11.38.12.Deal with transient in Object Serialization
11.38.13.Serialization Utilities