一般在以下几种情况下,我们可能会用到序列化:
a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;
b)当你想用套接字在网络上传送对象的时候;
c)当你想通过RMI传输对象的时候。
先通过一则简单示例来查看序列化的用法。
源码如下(SerialTest1.java):
1 /**
2 * 序列化的演示测试程序
3 *
4 * @author skywang
5 */
6
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.ObjectInputStream;
10 importjava.io.ObjectOutputStream;
11 importjava.io.Serializable;
12
13 public class SerialTest1 {
14 private static final StringTMP_FILE = ".serialtest1.txt";
15
16 public static void main(String[] args) {
17 // 将“对象”通过序列化保存
18 testWrite();
19 // 将序列化的“对象”读出来
20 testRead();
21 }
22
23
24 /**
25 * 将Box对象通过序列化,保存到文件中
26 */
27 private static void testWrite() {
28 try {
29 // 获取文件TMP_FILE对应的对象输出流。
30 //ObjectOutputStream中,只能写入“基本数据”或“支持序列化的对象”
31 ObjectOutputStream out = new ObjectOutputStream(
32 new FileOutputStream(TMP_FILE));
33 // 创建Box对象,Box实现了Serializable序列化接口
34 Box box = newBox("desk", 80, 48);
35 // 将box对象写入到对象输出流out中,即相当于将对象保存到文件TMP_FILE中
36 out.writeObject(box);
37 // 打印“Box对象”
38 System.out.println("testWritebox: " + box);
39
40 out.close();
41 } catch (Exception ex) {
42 ex.printStackTrace();
43 }
44 }
46 /**
47 * 从文件中读取出“序列化的Box对象”
48 */
49 private static void testRead() {
50 try {
51 // 获取文件TMP_FILE对应的对象输入流。
52 ObjectInputStream in = new ObjectInputStream(
53 new FileInputStream(TMP_FILE));
54 // 从对象输入流中,读取先前保存的box对象。
55 Box box =(Box) in.readObject();
56 // 打印“Box对象”
57 System.out.println("testRead box: " + box);
58 in.close();
59 } catch (Exception e) {
60 e.printStackTrace();
61 }
62 }
63 }
64
65
66 /**
67 * Box类“支持序列化”。因为Box实现了Serializable接口。
68 *
69 * 实际上,一个类只需要实现Serializable即可实现序列化,而不需要实现任何函数。
70 */
71 class Box implements Serializable {
72 private int width;
73 private int height;
74 private String name;
76 publicBox(String name, int width, int height) {
77 this.name= name;
78 this.width= width;
79 this.height= height;
80 }
81
82 @Override
83 public String toString() {
84 return"["+name+": ("+width+", "+height+") ]";
85 }
86 }
运行结果:
testWrite box: [desk: (80, 48) ]
testRead box: [desk:(80, 48) ]
源码说明:
(01) 程序的作用很简单,就是演示:先将Box对象,通过对象输出流保存到文件中;之后,再通过对象输入流,将文件中保存的Box对象读取出来。
(02) Box类说明。Box是我们自定义的演示类,它被用于序列化的读写。Box实现了Serialable接口,因此它支持序列化操作;即,Box支持通过 ObjectOutputStream去写入到输出流中,并且支持通过ObjectInputStream从输入流中读取出来。
(03) testWrite()函数说明。testWrite()的作用就是,新建一个Box对象,然后将该Box对象写入到文件中。
首先,新建文件TMP_FILE的文件输出流对象(即FileOutputStream对象),再创建该文件输出流的对象输出流(即ObjectOutputStream对象)。
a) 关于FileInputStream和FileOutputStream的内容,可以参考“java io系列07之 FileInputStream和FileOutputStream”。
b) 关于ObjectInputStream和ObjectOutputStream的的更多知识,可以参考“java io系列05之ObjectInputStream 和 ObjectOutputStream”
然后,新建Box对象。
最后,通过out.writeObject(box) 将box写入到对象输出流中。实际上,相当于将box写入到文件TMP_FILE中。
(04) testRead()函数说明。testRead()的作用就是,从文件中读出Box对象。
首先,新建文件TMP_FILE的文件输入流对象(即FileInputStream对象),再创建该文件输入流的对象输入流(即ObjectInputStream对象)。
然后,通过in.readObject() 从对象输入流中读取出Box对象。实际上,相当于从文件TMP_FILE中读取Box对象。
若要支持序列化,除了“自定义实现Serializable接口的类”之外;java的“基本类型”和“java自带的实现了Serializable接口的类”,都支持序列化。