Serializable详解

/**
 * Serializable(序列化)是一种将对象以一连串的字符描述;
 * 反序列化是一种将这些字节重构成一个对象的过程
 * 如何实现序列化:将需要序列化的对象实现Serializable接口就可以了
 */
public class Serializable implements java.io.Serializable {

    /**
     * 如果我们要创建一个序列化对象,首先要创造某些outPutStream,然后把这些outPutStream封装
     * 到objectPutStream,这时只需调用writeObject()方法就可以序列化,并将其发送给outPutStream
     * (对象的序列化是基于字节的,不能使用reader和writer等基于字符结构)
     */

    private static final long serializableUID = 1L;
    private String name = "sheep";
    private int age = 24;

    public static void main(String[] args) {
        try {
            //输出流名称为test.txt ,objectOutputStream能把object输出成字节流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("E:\\test.txt"));
            Serializable serializable = new Serializable();
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush(); //缓冲流
            objectOutputStream.close(); //关闭流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fan();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     */
    public static void fan() throws FileNotFoundException {
        ObjectInputStream ois = null; //局部变量必须初始化
        try {
            ois = new ObjectInputStream(new FileInputStream("E:\\test.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Serializable se = null;
        //有object向下转型为Serializable对象
        try {
            se =(Serializable)ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("name:"+se.name);
        System.out.println("age:"+se.age);
    }

}
运行结果:
name:sheep
age:24


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值