序列化
序列化就是把流中对象的属性、值写入到文件中
被序列化的类 必须实现Serializable接口
如: public class Student implements Serializable
bin表示二进制文件
package com.qian;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Demo06 {
public static void main(String[] args) throws Exception {
FileOutputStream fos=new FileOutputStream("r:\\stu.bin");
ObjectOutputStream oos= new ObjectOutputStream(fos);
Student ligan = new Student("李赣",20);
Student sundog=new Student("孙狗", 64);
ArrayList<Student> list=new ArrayList<>();
list.add(ligan);
list.add(sundog);
oos.writeObject(list);
oos.close();
System.out.println("序列化完毕");
}
}
serialVersionUID:序列化版本号ID
静态属性无法被序列化
package com.qian;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = -3151026672167488108L;
private String name;
private int age;
public static String country="中国";
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String name() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int age() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
反序列化
Java反序列化就是指把字节序列从硬盘中恢复为内存中Java对象的过程。
package com.qian;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class Demo07
{
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("r:\\stu.bin");
ObjectInputStream ois=new ObjectInputStream(fis);
Student s=(Student)ois.readObject();
Student s2=(Student)ois.readObject();
ois.close();
System.out.println("执行完毕");
System.out.println(s.toString());
}
}
报错原因:
黄色部分已经读取了,红色部分读不了,所以报错