zoukankan      html  css  js  c++  java
  • 类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)

    1.需要序列化的类

    import java.io.Serializable;
    /**
    * 必须继承 Serializable 接口才能实现序列化
    */
    public class Employee implements Serializable{
        /**
         * transient 关键字表示该字段无法序列化
         */
        private transient int age;
        private String name;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Employee(int age, String name) {
            this.age = age;
            this.name = name;
        }
        
        public Employee() {
        }
        
        @Override
        public String toString() {
            
            return "name:"+this.name+"  age:"+this.age;
        }
    }

    2.实现序列化

    package com.qiao.IOTest;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class ObjectInOutTest {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            write("test6.txt");
            read("test6.txt");
        }
        
        public static void write(String path) throws IOException{
            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
            Employee e = new Employee(11, "joey");
            out.writeObject(e);
            out.close();
        }
        
        public static void read(String path) throws IOException, ClassNotFoundException{
            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
            Object obj=in.readObject();
            if(null!=obj && obj instanceof Employee){
                Employee e = (Employee)obj;
                System.out.println(e.toString());
            }
        }
        
    }

    输出:name:joey  age:0

    因为age字段被transient关键字修饰,无法序列化,所以获得的值为0,而不是11

  • 相关阅读:
    前端之页面标签的图标修改
    分页, 解析器, 渲染器
    DRF的认证,频率,权限
    视图组件,路由组件,版本控制
    序列化组件
    Restful规范
    docker大全集
    哨兵和docker容器
    项目发布须知
    Linux之nginx
  • 原文地址:https://www.cnblogs.com/Iqiaoxun/p/6006353.html
Copyright © 2011-2022 走看看