类的序列化和反序列化

来源:互联网 发布:unity3d虚拟现实源码 编辑:程序博客网 时间:2024/05/21 22:23

要使一个类能进行序列化操作,并实现Serializable接口
如果类中的某些成员变量不想实现序列化,则需要在前面添加关键字transient

实体类

package cn.io;import java.io.Serializable;/** * @author Duoduo * @version 1.0 * @date 2017/4/16 22:43 */public class Employee implements Serializable {    private transient String name;// 不需要序列化    private double salary;    public Employee(String name, double salary) {        this.name = name;        this.salary = salary;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getSalary() {        return salary;    }    public void setSalary(double salary) {        this.salary = salary;    }}

测试类

package cn.io;import java.io.*;/** * 只有类实现了 Serializable 才能进行序列化操作 * @author Duoduo * @version 1.0 * @date 2017/4/16 22:43 */public class Test3 {    public static void main(String[] args) {        writeObject();        readObject();    }    /**     * 反序列化     */    public  static void readObject(){        File file = new File("/Users/Pengjinjin/Desktop/employee.txt");        ObjectInputStream objectInputStream = null;        try {            objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));           Object object = objectInputStream.readObject();           if( object instanceof  Employee){               Employee employee =(Employee)object;               System.out.println(employee.getSalary());           }        } catch (IOException e) {            e.printStackTrace();        } catch (ClassNotFoundException e) {            e.printStackTrace();        } finally {            if(objectInputStream!=null){                try {                    objectInputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    /**     * 序列化     */    public static void writeObject() {        File file = new File("/Users/Pengjinjin/Desktop/employee.txt");        ObjectOutputStream objectOutputStream = null;        try {            objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));            Employee employee = new Employee("employee",1000);            objectOutputStream.writeObject(employee);            objectOutputStream.flush();        } catch (IOException e) {            e.printStackTrace();        }finally {            if(objectOutputStream!=null){                try {                    objectOutputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

最后运行结果:获取到Employee的salary 为 1000

0 0
原创粉丝点击