序列化和反序列化

序列化

通过流传输写出对象就是序列化

1、序列化对象

    private static void writeObj() {
        Student201222 lg = new Student201222("lg", 21, 20);
        try (FileOutputStream outputStream = new FileOutputStream("D://object.bin");
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
            objectOutputStream.writeObject(lg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

序列化集合

    private static void writeArr() {
        List<Student201222> list = new ArrayList<>();
        Student201222 lg = new Student201222("lg", 21, 20);
        Student201222 ly = new Student201222("ly", 22, 9);
        list.add(ly);
        list.add(lg);
        try (FileOutputStream outputStream = new FileOutputStream("D://object.bin");
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
            objectOutputStream.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

反序列化

通过流传输读取对象就是反序列化

1、反序列化对象

    private static void readObj() {
        try (FileInputStream inputStream = new FileInputStream("D://object.bin");
             ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
            Student201222 lg = (Student201222) objectInputStream.readObject();
            System.out.println(lg.toString());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

2、反序列化集合

    private static void readArr() {
        try (FileInputStream inputStream = new FileInputStream("D://object.bin");
             ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
            List<Student201222> list = (ArrayList) objectInputStream.readObject();
            for (Student201222 student : list) {
                System.out.println(student.toString());
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

总结

/**
 * 序列化注意事项:
 *  1、序列化必须要实现Serializable接口
 *  2、序列化的类中的对象属性也必须实现Serializable接口
 *  3、序列化版本号serialVersionUID,保证序列化的类和反序列化的类是统一个类
 *  4、使用transient(瞬间的、瞬态)修饰的属性不能被序列化
 *  5、static修饰的属性不能被序列化
 *  6、序列多个对象,可用借助集合实现
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值