- package bxd;
- importjava.io.*;
- public class ObjectStreamDemo {
- public static voidreadObj()throws Exception {
- ObjectInputStream ois =newObjectInputStream(newFileInputStream("Person.object"));
- Person person = (Person) ois.readObject();
- System.out.println(person);
- ois.close();
- }
- public static voidwriteObj()throws Exception {
- ObjectOutputStream oos =newObjectOutputStream(newFileOutputStream("Person.object"));
- oos.writeObject(newPerson("lily", 39, "us"));
- oos.close();
- }
- public static voidmain(String[] args)throws Exception {
- // writeObj();
- readObj();
- }
- }
- /*
- 输出lily:0:cn, 因为age不会被序列化(使用初始值0), 静态变量country也不会被序列化(使用初始值cn).
- */
- classPersonimplements Serializable {
- public static final longserialVersionUID = 42L;// 强烈建议所有可序列化类都显式声明serialVersionUID
- private String name;
- transient intage;// 如果某个实例变量不需要被序列化, 可以使用transient修饰
- staticString country = "cn";// 序列化行为只针对Java堆(heap), 而静态变量不存在于heap.
- Person(String name, int age, String country) {
- this.name = name;
- this.age = age;
- this.country = country;
- }
- public String toString() {
- returnname + ":" + age + ":" + country;
- }
- }
来源: