类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)

Posted woqiaoxun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类的序列化和反序列化(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

 

以上是关于类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)的主要内容,如果未能解决你的问题,请参考以下文章

类的序列化和反序列化(ObjectOutputStream和ObjectInputStream)

JAVA 序列化和序列化

序列化和反序列化漏洞的简单理解

序列化和反序列化

反序列化为啥要找公开方法

java 序列化和反序列化