对象的序列化与反序列化
ObjectOutputStream对象序列化流
作用:把对象以流的形式写入道文件中保存
-
构造方法:ObjectOutputStream(OutputStream out)
-
特有的方法:
- void writeObject(Object obj)将指定的对象写入道ObjectOutputStream中
-
注意:序列化和反序列化的时候,会抛出NotSerializableException异常,类必须实现Serializable接口来开启序列化,这个接口也叫标记型接口
public static void main(String[] args)throws Exception {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("张三",20));
list.add(new Person("李四",19));
list.add(new Person("王五",22));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/PersonList.txt"));
oos.writeObject(list);
oos.close();
}
ObjectInputStream对象反序列化流
作用:把文件中保存的对象,以流的方式读取出来使用
-
构造方法:
- ObjectInputStream(InputStream in)参数为字节输入流
-
特有的成员方法:
- Object readObject() 从ObjectInputStream读取对象。
-
使用步骤:
- 创建ObjectInputStream对象,构造方法中传递字节输入流
- 使用ObjectInputStream对象中的readObject读取保存对象的文件
- 释放资源
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./javaBook/src/cn/edu/aku/unit10/Buffer/PersonList.txt"));
ArrayList<Person> list =(ArrayList<Person>) ois.readObject();
for (Person item :list) {
System.out.println(item.getName()+":"+item.getAge());
}
ois.close();
注意事项:
-
static关键字:
- 静态关键字,被static修饰的成员变量,不能被序列化
-
transient关键字:
-
transient只能修饰变量,不能修饰方法和类
-
瞬态关键字,被transient修饰的成员变量,不能被序列化
-
-
serialVersionUID的使用
- 序列化运行时使用一个称为serialVersionUID的版本号与每个可序列化类相关联,该序列号在反序列过程中用于验证序列化对象的发送者和接收者是否为该对象加载了与序列化兼容的类。如果接收者加载的该对象的类serialVersionUID与对应的发送者的类的版本号不同,则反序列化将会失败,导致InvalidClassException。可序列化类可以通过声明serialVersionUID的字段(该字段必须是static,funal,long类型的字段)显示声明自己的serialVersionUID;