java对象的反序列化和序列化

对象的序列化

package com.tedu.day1301;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/*
完成序列化
序列化:将java对象序列化到磁盘中
 */
public class Study_OOS01 {
    public static void main(String[] args) {
        try {
            // 创建ObjectOutputStream的序列化对象
            FileOutputStream out = new FileOutputStream("student.txt");
            ObjectOutputStream oos = new ObjectOutputStream(out);
            // 实现序列化
            Student stu = new Student("张飞",18,"北京");
            oos.writeObject(stu);
            // 释放流资源
            oos.close();
            System.out.println("对象序列化成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

//创建Student类
class Student implements Serializable {
    //成员变量
    private String name;
    private int age;
    private String addr;
    // 无参构造
    public Student(){
    }
    public Student(String name, int age, String addr) {
        this.name = name;
        this.age = age;
        this.addr = addr;
    }

    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;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", addr='" + addr + '\'' +
                '}';
    }
}

对象的反序列化

package com.tedu.day1301;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/*
实现反序列化
将磁盘文件转换为java对象
如何实现:ObjectInputStream
 */
public class Study_OIS01 {
    public static void main(String[] args) {
        try {
            // 创建ObjectInputStream对象
            FileInputStream in = new FileInputStream("student.txt");
            ObjectInputStream ois = new ObjectInputStream(in);
            // 使用readObject()进行反序列化
            Object obj = ois.readObject();
            // 向下转型
            Student st = (Student)obj;
            System.out.println(st.getName());
            ois.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
posted @ 2022-11-05 22:58  竹石2020  阅读(18)  评论(0编辑  收藏  举报