• 类的序列化和反序列化(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

  • 相关阅读:
    VS2017 C# winform 项目使用 sqlite (二)
    VS2017 C# winform 项目使用 sqlite (一)
    JS权威指南笔记(171页)-this关键字的作用域
    量化交易之下单函数和context对象
    量化交易策略基本框架
    初始量化交易
    金融量化之Tushare模块
    Python之基础算法介绍
    数据分析之Matplotlib和机器学习基础
    数据分析之Pandas
  • 原文地址:https://www.cnblogs.com/Iqiaoxun/p/6006353.html
Copyright © 2020-2023  润新知