Java学习笔记——序列化

目录

一、序列化相关概念

二、序列化 & 反序列化


一、序列化相关概念

序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。

整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。

序列化的用途

  • 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
  • 在网络上传送对象的字节序列。

序列化的实现

  • java.io.ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。只有实现了Serializable和Externalizable接口的类的对象才能被序列化。

  • java.io.ObjectInputStream代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。

二、序列化 & 反序列化

首先,我们先定义一个Student1对象类,之后再进行序列化和反序列化,相关代码如下:

import java.io.*;

class Student1 implements Serializable{
    public String name;
    public String sex;
    public int age;
    public float height;
    public float weight;

    public void Information() {
        System.out.println("name: " + name
                + ", sex: " + sex
                + ", age: " + age
                + ", height: " + height
                + ", weight: " + weight
        );
    }
}


public class Day37 {
    public static void main(String[] args) throws Exception, IOException{
        toSerialize();
        toDeserialize();
    }

    private static void toSerialize() throws FileNotFoundException, IOException {
        Student1 stu = new Student1();
        stu.name = "Jack";
        stu.sex = "man";
        stu.age = 18;
        stu.height = 188.0F;
        stu.weight = 80.0F;

        try {
            // 序列化到文件中
            FileOutputStream fileOut = new FileOutputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(stu);
            out.close();
            fileOut.close();
            System.out.println("序列化成功!");

        } catch (IOException i) {
            i.printStackTrace();
        }
    }

    private static void toDeserialize() throws FileNotFoundException, IOException{
        Student1 stu2 = null;
        try{
            FileInputStream filein = new FileInputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
            ObjectInputStream in = new ObjectInputStream(filein);
            stu2 = (Student1)in.readObject();
            in.close();
            filein.close();
            System.out.println("反序列化成功!");
        }catch (IOException | ClassNotFoundException i){
            i.printStackTrace();
        }

        stu2.Information();
    }
}
序列化成功!
反序列化成功!
name: Jack, sex: man, age: 18, height: 188.0, weight: 80.0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值