Java 序列化
什么是序列化
序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。
对象流
序列化一种用来处理对象流的机制。所谓对象流也就是将对象的内容进行流化,可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。
类 ObjectInputStream 和 ObjectOutputStream 是高层次的数据流,它们包含序列化和反序列化对象的方法。
你可以使用 ObjectOutputStream 来序列化一个对象,并把它发送到输出流:
publicfinalvoidwriteObject(Objectx)throwsIOException;
相似的,你也可以使用 ObjectInputStream 来反序列化一个对象:
publicfinalObjectreadObject()throwsIOException,ClassNotFoundException;
可序列化的对象
将需要被序列化的类实现 Serializable 接口,该接口没有需要实现的方法,implements Serializable 只是为了标注该对象是可被序列化。
publicclassEmployeeimplementsjava.io.Serializable{
publicStringname;
publicStringaddress;
publictransientintSSN;
publicintnumber;
publicvoidmailCheck(){
System.out.println("Mailing a check to "+name+" "+address);
}
}
请注意,一个类的对象要想成功的序列化,必须满足 2 个条件:
该类必须实现 java.io.Serializable 接口;
该类的所有属性必须是可序列化的,不能序列化的属性必须注明是短暂的(transient);
序列化对象
ObjectOutputStream 类用来序列化一个对象,输出的文件的默认扩展名为.ser。
publicstaticvoidmain(String[]args){
Employeee=newEmployee();
e.name="Reyan Ali";
e.address="Phokka Kuan, Ambehta Peer";
e.SSN=11122333;
e.number=101;
try{
FileOutputStreamfileOut=newFileOutputStream("/tmp/employee.ser");
ObjectOutputStreamout=newObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOExceptioni){
i.printStackTrace();
}
}
反序列化对象
publicstaticvoidmain(String[]args){
Employeee=null;
try{
FileInputStreamfileIn=newFileInputStream("/tmp/employee.ser");
ObjectInputStreamin=newObjectInputStream(fileIn);
e=(Employee)in.readObject();
in.close();
fileIn.close();
}catch(IOExceptioni){
i.printStackTrace();
return;
}catch(ClassNotFoundExceptionc){
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.