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修饰的成员变量,不能被序列化
-