Java基础-序列化流(对象流)详细学习笔记
由于jvm的机制,对象在程序运行结束后会被回收,如果我们需要讲对象持久化存储,可以考虑把对象以流的形式存储在硬盘上或者数据库中,这个过程就是序列化流
-
对象输出流:ObjectOutputStream(将Java 对象的基本数据类型和图形写入 OutputStream)
-
对象输入流:ObjectInputStream (对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化(提取回来))
创建对象
/*以学生实体类为例*/
/*
*public class Student implements Serializable
*被序列化的实体类需实现Serializable接口
*/
Student student = new Student(101,"武松") ;
Student student1 = new Student(102,"刘备") ;
/*多个对象需要以集合的方式序列化*/
List<Student> sList = new ArrayList<>() ;
sList.add(student);
sList.add(student1);
/*对象流创建*/
ObjectOutputStream out = null ;
ObjectInputStream in = null ;
out = new ObjectOutputStream(new FileOutputStream("testIO2.txt")) ;//参数为outputstream对象
in = new ObjectInputStream(new FileInputStream("testIO2.txt")) ;//参数为inputstream对象
序列化
out.writeObject(sList); //结果(对象数据)是不支持读懂的,反序列化才行
out.flush(); //对象流需要刷新
反序列化
Object o = in.readObject();
List<Student> lists = (List<Student>)o ;
System.out.println(lists);
/*结果
*[Student{sno=101, name='武松', books=[]}, Student{sno=102, name='刘备', books=[]}]
*/