11.1 概念
- Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。
- 将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。
- 整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。
类 ObjectInputStream 和 ObjectOutputStream 是高层次的数据流,它们包含反序列化和序列化对象的方法。
11.2 条件
请注意,一个类的对象要想序列化成功,必须满足两个条件:
该类必须实现 java.io.Serializable 接口。
- 该类的所有属性必须是可序列化的。如果有一个属性不是可序列化的,则该属性必须注明是短暂的。
11.3 序列化对象
ObjectOutputStream 类用来序列化一个对象,如下的 SerializeDemo 例子实例化了一个 Employee 对象,并将该对象序列化到一个文件中。该程序执行后,就创建了一个名为 employee.ser 文件。public class Employee implements java.io.Serializable{public String name;public String address;public transient int SSN; // 短暂的public int number;public void mailCheck(){System.out.println("Mailing a check to " + name + " " + address);}}
public class SerializeDemo{public static void main(String [] args){Employee e = new Employee();e.name = "Reyan Ali";e.address = "Phokka Kuan, Ambehta Peer";e.SSN = 11122333;e.number = 101;try{FileOutputStream fileOut = new FileOutputStream("/employee.ser");ObjectOutputStream out = new ObjectOutputStream(fileOut);out.writeObject(e);out.close();fileOut.close();System.out.printf("Serialized data is saved in /employee.ser");}catch(IOException i){i.printStackTrace();}}}
11.4 反序列化对象
下面的 DeserializeDemo 程序实例了反序列化,/employee.ser 存储了 Employee 对象。public class DeserializeDemo{public static void main(String [] args){Employee e = null;try{FileInputStream fileIn = new FileInputStream("/employee.ser");ObjectInputStream in = new ObjectInputStream(fileIn);e = (Employee) in.readObject();in.close();fileIn.close();}catch(IOException i){i.printStackTrace();return;}catch(ClassNotFoundException c){System.out.println("Employee class not found");c.printStackTrace();return;}System.out.println("Deserialized Employee..."); // Deserialized Employee...System.out.println("Name: " + e.name); // Name: Reyan AliSystem.out.println("Address: " + e.address); // Address: Phokka Kuan, Ambehta PeerSystem.out.println("SSN: " + e.SSN); // SSN: 0System.out.println("Number: " + e.number); // Number: 101}}/* 当对象被序列化时,属性 SSN 的值为 111222333,但是因为该属性是短暂的,该值没有被发送到输出流。所以反序列化后 Employee 对象的 SSN 属性为 0。*/
