【Java】序列化&反序列化

Student.java

package LearnJava15;

import java.io.Serializable;

public class Student implements Serializable {
    private String name;
    private 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;
    }
}

 

 

package LearnJava15;

import java.io.*;

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write();
        read();
    }
//反序列化
    private static void read() throws IOException, ClassNotFoundException {
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\oss.txt"));
        Object obj=ois.readObject();
        Student s=(Student) obj;
        System.out.println(s.getName()+","+s.getAge());
        ois.close();
    }
//序列化
    private static void write() throws IOException {
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\oss.txt"));
        Student s=new Student("小A",22);
        oos.writeObject(s);
        oos.close();
    }
}

 

posted @ 2022-04-27 11:31  木子欢儿  阅读(35)  评论(0编辑  收藏  举报