Java序列化与反序列化

发布时间 2023-10-12 16:37:42作者: geekbky
  • ?定义:

    • 序列化:把对象转化可传输的字节序列的过程称为序列化。
    • 反序列化:把字节序列还原为对象的过程称为反序列化。
  • java如何实现序列化:

public class Student implements Serializable {//继承Serializable接口
    @Serial
    private static final long serialVersionUID = -4027734259721761657L;
     String name;
     int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class StudentTest {
    /**
     * 测试序列化
     */
    @Test
public void testSerialization(){
    Student stu = new Student("张三", 19);
    try {
        FileOutputStream fileOutputStream = new FileOutputStream("D://Student.ser");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(stu);
        System.out.println("序列化成功!");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
    /**
     * 测试反序列化
     */
    @Test
    public void testDeserialization() {
        try {
            FileInputStream fileInputStream = new FileInputStream("D://Student.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Student stu = new Student();
            stu =(Student) objectInputStream.readObject();
            System.out.println(stu.getName());
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

运行结果:
Student.ser
学生.name