java序列化与反序列化

实现Serializable

import java.io.Serializable;

public class Employee implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public String name;
    public String address;
    public transient int SSN;
    public int number;

    public void mailCheck() {
        System.out.println("Mailing a check to " + name + " " + address);
    }
}

序列化

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeDemo {
    public static void main(String[] args) {
        Employee e = new Employee();
        e.name = "Reyan Ali";
        e.address = "Phokka Kuan, Ambehta Peer";
        e.SSN = 11122333;
        e.number = 101;

        try

        {
            // 获取文件输出流
            FileOutputStream fileOut = new FileOutputStream("./employee.ser");
            // 将文件输出流加工成对象输出流
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            // 向对象输出流中写入特定的对象实例
            out.writeObject(e);
            // 关闭对象输出流
            out.close();
            // 关闭文件输出流
            fileOut.close();
            System.out.println("Serialized data is saved in ./employee.ser");

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

    }
}

反序列化

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeDemo {
    public static void main(String[] args) {
        Employee e = null;
        try {
            FileInputStream fileIn = new FileInputStream("./employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        } catch (ClassNotFoundException c) {
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
        } catch (Exception i) {
            i.printStackTrace();
            return;
        }
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + e.name);
        System.out.println("Address: " + e.address);
        System.out.println("SSN: " + e.SSN);
        System.out.println("Number: " + e.number);
    }
}

小结

  1. 序列化Serializable 是个标记接口
  2. 文件流一般都是其它流的底层引用,上层的对象流,二流遵循先进后出
  3. 以内存角度来理解输入输出概念,从程序写入数据到其他位置,则是输出流,将数据读入程序中则是输入流
  4. 读取数据就是输入流,写入数据就是输出流
  5. 错误捕获范围由近到远,即精准到模糊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值