1.定义
对象流是处理流的一种,其有两个类:
ObjectOutputStream
和ObjectInputStream
ObjectOutputStream:即序列化过程-----是将内存中的对象写到磁盘中、文件中。
ObjectInputStream:即反序列化过程-----是将文件中的内容接收,恢复为Java对象。
序列化和反序列化的核心作用即:对象的保存和重建。
2.举例
学生类
package Serializable_Demo;
import java.io.Serializable;
public class Student implements Serializable {
//自定义类要指明serialVersionUID
//不然会报错:即序列化和反序列化的serialVersionUID没有对应上
private static final long serialVersionUID = 1L;
String name;
String sex;
String sno;
int age;
public Student() {
}
public Student(String name, String sex, String sno, int age) {
this.name = name;
this.sex = sex;
this.sno = sno;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", sno='" + sno + '\'' +
", age=" + age +
'}';
}
}
注意:
自定义类一定要指明serialVersionUID
,不然会报以下错误:序列化和反序列化的serialVersionUID没有对应上。serialVersionUID参数的主要作用是用来验证Java序列化版本的一致性。
序列化
package Serializable_Demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class OOS_Demo {
public static void main(String[] args) {
//序列化
ObjectOutputStream oos = null;
try {
//得到的Java对象信息存储到student.txt中 向文件中写入对象
oos = new ObjectOutputStream(new FileOutputStream("studentInfo.txt"));
Student s1 = new Student("张三", "male", "20201212", 18);
Student s2 = new Student("李四", "female", "20201213", 19);
Student s3 = new Student("王五", "male", "20201214", 21);
oos.writeObject(s1);
//在写的过程中有一个缓冲区,缓冲区满了之后才会把缓冲区的数据写到磁盘之中
//但是有可能缓冲区填不满,导致这一部分数据无法写入到磁盘中
//所以有一个刷新操作flush():将缓冲区的数据发送出去
oos.flush();
oos.writeObject(s2);
oos.flush();
oos.writeObject(s3);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (oos != null) {
try {
System.out.println("写入成功!");
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
将对象转为字节数据,存入到自己定义的文件地址中:
反序列化
package Serializable_Demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class OIS_Demo {
public static void main(String[] args) {
//反序列化
ObjectInputStream ois = null;
try {
//读取文件中的数据
ois = new ObjectInputStream(new FileInputStream("studentInfo.txt"));
Student student1 = (Student) ois.readObject();
System.out.println(student1.toString());
Student student2 = (Student) ois.readObject();
System.out.println(student2.toString());
Student student3 = (Student) ois.readObject();
System.out.println(student3.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
将字节数据读取为内存中的对象,可进行输出到控制台: