信息发布→ 登录 注册 退出

深入理解Java序列化与反序列化

发布时间:2026-01-11

点击量:
目录
  • 一、前言
    • 1.1 String
    • 1.2 Integer
  • 二、案例
    • 2.1 编写大象类
    • 2.2 大象测试类
  • 三、运行结果

    一、前言

    序列化:将对象转换为二进制序列在网络中传输或保存到磁盘

    反序列化:从网络或磁盘中将二进制序列转换为对象

    注意:

    • 对象必须实现Serializable接口

    • 对象的所有属性都要能序列化(Integer,Byte等都进行了序列化)

    1.1 String

    1.2 Integer

    二、案例

    2.1 编写大象类

    public class Elephant implements Serializable {
        private String name;
        private String age;
        private String sex;
      
        public Elephant(String name, String age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Elephant{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    }
    

    2.2 大象测试类

    public class ElephantTest {
        public static  final  String PATH = "D:\\elephant";
        static  void write(Elephant elephant){
            //创建对象输出流
            try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {
               //写入对象
                out.writeObject(elephant);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        static Object read(){
            //创建对象输出流
            try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) {
                //写入对象
               return in.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static void main(String[] args) {
            Elephant elephant7 = new Elephant("小红象", "18", "男");
            write(elephant7);
          	Elephant elephant1 = (Elephant) read();
          	System.out.println(elephant1);
            System.out.println(elephant7);
            System.out.println(elephant1==elephant7);
        }
    }
    

    三、运行结果

    写入D盘的对象:

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!