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

原文地址:https://www.cnblogs.com/Iqiaoxun/p/6006353.html