zoukankan      html  css  js  c++  java
  • 序列化和反序列化

    1.序列化:将内存中对象的状态或者信息转换成持久化的过程。

    2.反序列化:把持久化对象变成内存中的一个对象的过程。

    3.序列化目的:

      01.使自定义的对象持久化,对象本身就是内存中的

      02.把对象从一个地方传递到另一个地方

      03.使程序具有维护性

    4.实现对象序列化的方法

      01.让对象所属的类实现Serializable接口,这个类就可以序列化了

      02.Serializable:只是一个能否被序列化的标记。

    5.反序列化要求注意:

      需要和序列化时候的包名一致不然就没法序列化

    public class Student implements Serializable {
    
        private Integer id;// 编号
        private String name;// 姓名
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Student(Integer id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
    
        public Student() {
            super();
        }
    
        @Override
        public String toString() {
            return "Student [id=" + id + ", name=" + name + "]";
        }
    
    }
    Serializable
    @Test
        public void test01() throws Exception {
            // 首先实例化一个对象
            Student stu = new Student(1, "哈哈");
            // 序列化,从内存中放入持久化的介质中,输出流
            FileOutputStream stream = new FileOutputStream("f:/student.txt");
            ObjectOutputStream putStream = new ObjectOutputStream(stream);
            // 开始持久化
            putStream.writeObject(stu);
            putStream.close();
            stream.close();
        }
    ObjectOutputStream
    @Test
        public void test02() throws Exception {
            // 从文件中把对象拿到内存中输入流
            FileInputStream fStream = new FileInputStream("f:/student.txt");
            ObjectInputStream stream = new ObjectInputStream(fStream);
            // 读取文件中的对象
            Student student = (Student) stream.readObject();
            System.out.println(student);
            stream.close();
            fStream.close();
        }
    ObjectInputStream
  • 相关阅读:
    Centos 7环境下配置MySQL 5.7读写分离
    Centos 7环境下安装配置MySQL 5.7
    Hadoop 2.8集群安装及配置记录
    ASP.NET Core 1.1版本之Hello word
    Hadoop版Helloworld之wordcount运行示例
    SSH配置免密登陆设置汇总
    最小安装模式下Centos7.*网卡启动配置
    骚扰式管理
    项目团队之分工协作
    利用微软AntiXss Library过滤输出字符,防止XSS攻击
  • 原文地址:https://www.cnblogs.com/milu0620/p/7002913.html
Copyright © 2011-2022 走看看