自定义对象的序列化和反序列化(readObject-writeObject)

文章介绍了如何在Java中使用序列化(writeObject)和反序列化(readObject)实现User类的对象持久化,通过ObjectOutputStream和ObjectInputStream操作文件object.txt。
摘要由CSDN通过智能技术生成
public class Test6 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User zs = new User("zs", 1);
        write(zs);
        User user = (User) read();
        System.out.println(zs);
        System.out.println(user);
        System.out.println(zs==user);
    }

    static void write(Object o) throws IOException {
        ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream("f://object.txt"));
        outputStream.writeObject(o);
        outputStream.flush();
        outputStream.close();
    }

    static Object read() throws IOException, ClassNotFoundException {
        ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream("f://object.txt"));
        Object o = inputStream.readObject();
        inputStream.close();
        return o;
    }
}

class User implements Serializable {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    @Serial
    private void writeObject(ObjectOutputStream outputStream) throws IOException {
    	// 需要序列化的对象属性
        System.out.println("自定义write...");
        outputStream.writeObject(name);
        outputStream.writeInt(age);
    }

    @Serial
    private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
    	// 需要反序列化的属性,和写出时的顺序一致
        System.out.println("自定义read...");
        this.name= (String) inputStream.readObject();
        this.age=(Integer) inputStream.readInt();
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值