Java Serializable序列号和反序列化

来源:互联网 发布:东邪西毒黄药师知乎 编辑:程序博客网 时间:2024/06/05 16:55

当一个类实现了Serializable接口(该接口仅为标记接口,不包含任何方法定义),表示该类可以序列化.序列化的目的是将一个实现了Serializable接口的对象转换成一个字节序列,可以 把该字节序列保存起来(例如:保存在一个文件里),以后可以随时将该字节序列恢复为原来的对象。甚至可以将该字节序列放到其他计算机上或者通过网络传输到其他计算机上恢复,只要该计 算机平台存在相应的类就可以正常恢复为原来的对象。
//序列化一个对象(存储到一个文件)
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“person”));
oos.writeObject(“Hello world\n”);
oos.writeObject(new Person(“BOB”, “123456”));
oos.close();

//反序列化,将该对象恢复(存储到一个文件)
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“person.out”));
String s = (String)ois.readObject();
Person p = (Person)ois.readObject();
System.out.println(s + p);

这个我的个人理解是ByteArrayOutputStream是用来缓存数据的(数据写入的目标(output stream原义)),向它的内部缓冲区写入数据,缓冲区自动增长,当写入完成时可以从中提取数据。由于这个原因,ByteArrayOutputStream常用于存储数据以用于一次写入
//序列化一个对象(存储到字节数组)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos2 = new ObjectOutputStream(baos);
oos2.writeObject(“Save Obj Data:\n”);
oos2.writeObject(new Person(“John”, “654321”));
oos2.close();

当需要这个缓存数据的时候取出来使用
//反序列化,将该对象恢复(存储到字节数组)
ObjectInputStream ois2 = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
s = (String)ois2.readObject();
p = (Person)ois2.readObject();
System.out.println(s + p);

下面测试一下

public class Persion implements Serializable {    public String name;    public String password;    public Persion(String name,String password){        this.password = password;        this.name = name;    }public static void save1(){    try{        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("persion"));        outputStream.writeObject("hello world/n");        outputStream.writeObject(new Persion("bob","12345"));        outputStream.close();    }catch (Exception e){        e.printStackTrace();    }finally {    }}public static void read1(){    try {        ObjectInputStream input = new ObjectInputStream(new FileInputStream("persion"));        String str =  (String)input.readObject();        System.out.println(str);        Persion persion = (Persion)input.readObject();        System.out.println(persion.name+" "+persion.password);    }catch (Exception e){        e.printStackTrace();    }finally {    }}    public static void main(String[] args) {        save1();        read1();    }}
阅读全文
0 0
原创粉丝点击