对象的序列化:把java对象转换为字节序列的过程。
对象的反序列化:把字节序列恢复为java对象的过程。
对象的序列化主要有两种用途:
(1)把对象的字节序列永久保存到硬盘上,通常存放在一个文件中;
(2)在网络上传送对象的字节序列。
JDK类库中的序列化API
(1)java.io.ObjectOutputStream 代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。
(2) java.io.ObjectInputStream 代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们发序列化成一个对象,并将其返回。
注:只有实现了Serializable或Externalizable接口的类的对象才能被序列化,否则ObjectOuputStream的writeObject(Object obj)方法会抛出IOException。
对象的序列化主要包括以下步骤:
(1)创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\objectFile.obj"));
(2)通过对象输出流的writeObjec(Object obj)方法写对象:
out.writeObject("hello"); //写一个String对象
out.writeObject(new Date()); //写一个Date对象
对象的反序列化主要包括以下步骤:
(1)创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\objectFile.obj")));
(2)通过对象输入流的readObject()方法读取对象:
String obj1 = (String)in.readObject(); //读取一个String对象
Date obj2 =(Date)in.readObject(); //读取一个Date对象
【例】对象的序列化与反序列化简单实现
public class ObjectSerialSample {
//序列化对象存储路径
private static final String objectFilePath ="d:\\objectFile.obj";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(objectFilePath));
String obj1 ="hello";
Date obj2 = new Date();
Customer obj3 = new Customer("yw",25);
//序列化对象
out.writeObject(obj1);
out.writeObject(obj2);
out.writeObject(obj3);
out.writeInt(1234);//写入基本类型的数据
out.close();
//反序列化
ObjectInputStream in = new ObjectInputStream(new FileInputStream(objectFilePath));
String obj11 = (String)in.readObject();
System.out.println("obj11="+obj11);
System.out.println("obj11==obj1:"+(obj11==obj1));
Date obj22 =(Date)in.readObject();
System.out.println("obj22:"+obj22);
System.out.println("obj22==obj2:"+(obj22==obj2));
Customer obj33 = (Customer)in.readObject();
System.out.println("obj33:"+obj33);
System.out.println("obj33==obj3:"+(obj33==obj3));
//读取基本类型的数据
int var = in.readInt();
System.out.println("var:"+var);
in.close();
}
在String、Date和Customer对象进行反序列化时,都没有调用类的构造方法,而是直接根据它们的序列化数据在内存中创建新的对象