欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

序列化与反序列化

程序员文章站 2022-04-09 13:09:22
...

引用类型(对象)保留数据+类型

反序列化    输入流:ObjectInputStream     readObject()

序列化       输出流:ObjectOutputStream    writeObject()

注意:

1、先序列化后反序列化,顺序保持一致

2、不是所有对象都可以序列化,java.Io.Serializable

     不是所有属性都需要序列化,transient

import java.io.*;

/**
 * 反序列化 输入流:ObjectInputStream
 * 序列化   输出流:ObjectOutputStream
 * 先序列化后反序列化,
 */
public class Demo09 {
    public static void main(String[] args) {
        try {
            seri("D:/test.txt");
            read("D:/test.txt");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static void read(String destPath) throws IOException, ClassNotFoundException {
        //数据源
        File dest=new File(destPath);
        //选择流
        ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream(dest)));
        //操作
        Object obj=ois.readObject();
        if(obj instanceof Person){
            Person person=(Person)obj;
            System.out.println(person.getName());
            System.out.println(person.getSalary());
        }
        ois.close();
    }

    public static void seri(String testPath) throws IOException {
        Person person=new Person("zhang",90000);
        File test=new File(testPath);
        //选择流
        ObjectOutputStream dos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(test)));
        
        dos.writeObject(person);
        dos.flush();
        dos.close();
    }

}
import java.io.Serializable;

public class Person implements Serializable {
    private transient String name;
    private double salary;

    public Person(String name,double salary) {
        this.name = name;
        this.salary=salary;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

相关标签: io