首页 > 代码库 > 毕向东_Java基础视频教程第21天_IO流(1)

毕向东_Java基础视频教程第21天_IO流(1)

第21天-01-IO流(对象的序列化)

ObjectInputStream与ObjectOutputStream

  • 被操作的对象需要实现Serializable接口(标记接口)
  • 非必须, 但强烈建议所有可序列化类都显式声明serialVersionUID
package bxd;

import java.io.*;

public class ObjectStreamDemo {
    public static void readObj() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Person.object"));
        Person person = (Person) ois.readObject();
        System.out.println(person);
        ois.close();
    }

    public static void writeObj() throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.object"));
        oos.writeObject(new Person("lily", 39, "us"));
        oos.close();
    }

    public static void main(String[] args) throws Exception {
        // writeObj();
        readObj();
    }
}

/*
输出lily:0:cn, 因为age不会被序列化(使用初始值0), 静态变量country也不会被序列化(使用初始值cn).
*/
class Person implements Serializable {

    public static final long serialVersionUID = 42L;  // 强烈建议所有可序列化类都显式声明serialVersionUID
    private String name;
    transient int age;             // 如果某个实例变量不需要被序列化, 可以使用transient修饰
    static String country = "cn";  // 序列化行为只针对Java堆(heap), 而静态变量不存在于heap.

    Person(String name, int age, String country) {
        this.name = name;
        this.age = age;
        this.country = country;
    }

    public String toString() {
        return name + ":" + age + ":" + country;
    }
}

 

毕向东_Java基础视频教程第21天_IO流(1)