序列化的基本操作

一.在工作中看到了项目中很多类都继承了序列化接口,自己也上网查阅了一些关于实现序列化的好处
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方法实现读写操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值