序列化的基本操作

来源:互联网 发布:照片模板软件 编辑:程序博客网 时间:2024/06/05 21:05

一.在工作中看到了项目中很多类都继承了序列化接口,自己也上网查阅了一些关于实现序列化的好处
1:把对象的字节保存在硬盘上
2:用于在网络上数据之间的传送

创建一个实体类继承序列化接口

package IO;import java.io.Serializable;/** * Created by yx on 2017/8/26. */public class Student implements Serializable{    private String name;    private String address;    private int age;    Student(String name,String address,int age){        this.name=name;        this.address=address;        this.age=age;    }    @Override    public String toString() {        return name+","+address+","+age;    }}

序列化操作

package IO;import java.io.*;/** * Created by yx on 2017/8/26. * 关于序列化的操作 */public class Demo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        /**         * 进行序列化操作,将类的数据存放到文本中         * */        String path="G:\\IO流\\序列化.txt";        Student student=new Student("张三","深圳",23);        ObjectOutputStream ob=new ObjectOutputStream(new FileOutputStream(new File(path)));        ob.writeObject(student);        ob.flush();        ob.close();        /*        *   反序列化操作        * */        ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File(path)));        Student t= (Student) in.readObject();        System.out.println(t);        in.close();      }}

ObjectInputStream与ObjectOutputStream所读写的类必须要实现Serializable接口,通过对应的writeObject和readObject方法实现读写操作。

原创粉丝点击