【基础】 ---- 序列化和反序列化

目录

  1. 什么是序列化和反序列化
  2. 为什么要序列化
  3. 如何使用

1.序列化和反序列化

  • 把对象转换为字节序列的过程称为对象的序列化。
    serialize Object → File : create an ObjectOutputStream with a FileOutputStream.
    OutputStream os=new FileOutputStream(“a.txt”);
    serialize Object → sequences of bytes →File
    1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;
    2) 通过对象输出流的writeObject()方法写对象。
  • 把字节序列恢复为对象的过程称为对象的反序列化。
    deserialize File→ Object :create an ObjectInputStream with a FileInputStream.
    InputStream os=new FileInputStream(“a.txt”);
    File → sequences of bytes →serialize Object
    1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;
    2) 通过对象输入流的readObject()方法读取对象
    在这里插入图片描述

2.为什么要序列化

  • 在JVM级别,对象是在堆中创建的;在计算机结构中,它是在内存中创建的,在程序运行完,对象消失。序列化可以长久的保存此对象的数据。
  • 需要存储在磁盘上或通过网络传输的数据结构,序列化是一个很好的解决方案。磁盘或网络知道如何存储或传输数据,但它们不了解特定语言存储数据的方式。序列化为语言或编程环境提供了将其数据结构转换为标准格式的标准过程。

3.如何使用

@Test
    public void test2(){
        File file = new File("D:/test.txt");

        Role role = new Role(1L, "role", "note");

        // 序列化
        // serialize Object → sequences of bytes →File
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(role);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化
        // File → sequences of bytes →serialize Object
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            Role role1 = (Role) in.readObject();
            System.out.println(role1);
            System.out.println(role1.equals(role));
       } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
public class Role implements Serializable {
    //​序​列​化​的​版​本​号​,凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量
    private static final long serialVersionUID = 4603642343377807741L;
    private Long id;
    private String roleName;
    private String note;
    /**setter and getter **/
}

参考:
https://blog.csdn.net/jiangshangchunjiezi/article/details/105515489?depth_1-utm_source=distribute.pc_feed.185512&utm_source=distribute.pc_feed.185512

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值