Java-Serialize and Deserialize

来源:互联网 发布:卧龙大数据 上市 编辑:程序博客网 时间:2024/05/22 03:09

Java提供了一个机制叫做:对象序列化(Object Serialization)可以将Java对象的类型信息和对象携带的数据信息持久化写入到文件, 然后在另外的程序中读出保持原样.

这样一来, 一个对象可以在A地持久化之后, 传到B处使用.

与之有关的类分别是ObjectInputStreamObjectOutputStrream; 要使一个类的对象可以被持久化, 那么这个类必须实现Serializable接口

//希望被序列化的类public class Person implements Serializable{    long id;    String name;    int age;    public Person(long id, String name, int age) {        this.id = id;        this.name = name;        this.age = age;    }    @Override    public String toString() {        return "Person{" +                "id=" + id +                ", name='" + name + '\'' +                ", age=" + age +                '}';    }}public class Test {    public static void main(String[] args) throws Exception{        Person p = new Person(12, "闫家洪", 24);        //序列化后的文件        String  fp = "F:/test/person2.obj";        FileOutputStream fos = new FileOutputStream(fp);        ObjectOutputStream oos = new ObjectOutputStream(fos);        //序列化关键方法        oos.writeObject(p);        //记得关闭流        oos.close();        fos.close();        //反序列化        FileInputStream fis = new FileInputStream(fp);        ObjectInputStream ois = new ObjectInputStream(fis);        Person p1 = (Person) ois.readObject();        ois.close();        fis.close();        //打印反序列化后的对象        System.out.println(p1);    }}

参考文章:
Tutorials Point: Java Serialization