1.参与序列化的对象必须实现Serializable接口,起到相应的标识作用,Java虚拟机会给该类自动生成一个序列化版本号
2. java通过类名+序列化版本号的方式进行区分,transient关键字描述的属性不参与序列化
package com.javastudy.example10;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ObjectOut_In_Stream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1=new Student("1","h",22);
//序列化
/*
参与序列化的对象必须实现Serializable接口,起到相应的标识作用,Java虚拟机会给该类自动生成一个序列化版本号
java通过类名+序列化版本号的方式进行区分,transient关键字描述的属性不参与序列化
*/
ObjectOutputStream oop=new ObjectOutputStream(new FileOutputStream("ObjectOut_In_Stream_test"));
oop.writeObject(s1);
oop.flush();
oop.close();
System.out.println("序列化结束!!!");
System.out.println("开始反序列化!!!");
//反序列化
ObjectInputStream ooi=new ObjectInputStream(new FileInputStream("ObjectOut_In_Stream_test"));
Object obj = ooi.readObject();
System.out.println(obj);
ooi.close();
System.out.println("反序列化结束!!!");
System.out.println("===========================以下为批量序列化与反序列化============================");
//一次性序列化多个对象
List<Student> list=new ArrayList<>();
list.add(new Student("2","z",23));
list.add(new Student("3","k",24));
list.add(new Student("4","l",25));
ObjectOutputStream oopmore=new ObjectOutputStream(new FileOutputStream("MoreObjectOut_In_Stream_test"));
oopmore.writeObject(list);
oopmore.flush();
oopmore.close();
//反序列化
ObjectInputStream ooimore=new ObjectInputStream(new FileInputStream("MoreObjectOut_In_Stream_test"));
List<Student> list1=(List<Student>)ooimore.readObject();
for (Student student:list1) {
System.out.println(student);
}
ooimore.close();
}
}
运行结果