注意事项
- 序列化类必须要实现Serializable接口
- 序列化类中对象属性要求实现Serializable接口
- serialVersionUID 序列化版本ID,保证序列化的类和反序列化的类是同一个类
- transient(瞬间的)修饰属性,这个属性就不能序列化了
- 静态属性也不能被序列化
- 序列化多个对象,可以借助集合实现
package stream;
import java.io.Serializable;
/*
学生类
*/
public class Student implements Serializable {//标记这个类可以序列化
/*
serialVersionUID 序列化版本ID
*/
private static final long serialVersionUID = 100L;
private String name;
private transient int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student[name=" + name + ", age=" + age + "]";
}
}
package stream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
/*
使用ObjectOutputStream实现对象的序列化
要求:序列化必须要实现Serializable接口
*/
public class Demo07 {
public static void main(String[] args) throws Exception{
//1.创建对象流
FileOutputStream fos = new FileOutputStream("e:\\stu.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//2.序列化(写入操作)
Student zhangsan = new Student("张三",20);
Student lisi = new Student("李四",18);
ArrayList<Student> list = new ArrayList<>();
list.add(zhangsan);
list.add(lisi);
oos.writeObject(list);
//3.关闭
oos.close();
System.out.println("序列化完毕");
}
}
package stream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
/*
使用ObjectIntputStream实现反序列化(读取重构对象)
*/
public class Demo08 {
public static void main(String[] args) throws Exception{
//1.创建对象流
FileInputStream fis = new FileInputStream("e:\\stu.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
//2.读取文件(反序列化)
// Student s = (Student)ois.readObject();
ArrayList<Student> list =(ArrayList<Student>)ois.readObject();
//3.关闭
ois.close();
System.out.println("执行完毕");
System.out.println(list);
}
}