java序列化(对象流)

java序列化(对象流)


序列化

  • 目的:将对象保存到硬盘中,或者网络中传输对象
  • 机制:将Java对象转换为字节序列,序列可以保存硬盘,或网络传输
  • 代码:实现Serializable或者Externalizable接口
  • 序列化版本标识符:private static final long serialVersionUID
  • 注意:不能序列化static修饰的成员变量;对象中的任何成员变量必须实现Serializable接口
class Person implements Serializable {
    private static final long serialVersionUID = 124213453255L;
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

对象流

  • ObjectOutputStream:将Java对象写入IO流(序列化Serialize)
  • ObjectInputStream:从IO流中恢复Java对象
  • 注意:不能序列化static修饰的成员变量;对象中的任何成员变量必须实现Serializable接口
@Test
    public void testObjectOutputStream() {
        Person p1 = new Person("张三",20);
        Person p2 = new Person("李四",20);
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("person.txt"));
            oos.writeObject(p1);
            oos.flush();
            oos.writeObject(p2);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
@Test
    public void testObjectInputStream() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("person.txt"));
            Person p1 = (Person)ois.readObject();
            System.out.println(p1);
            Person p2 = (Person)ois.readObject();
            System.out.println(p2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

Person [name=张三, age=20]
Person [name=李四, age=20]

你可能感兴趣的:(java)