JAVA_基础IO流对象流(三)

处理流:对象流

ObjectInputStreamOjbectOutputSteam用于存储和读取基本数据类型数据或对象的处理流。可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

序列化:用ObjectOutputStream类保存基本类型数据或对象的机制。
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

对象序列化机制

序列化:将内存中的Java对象转换成二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点(ObjectOutputStream)。

反序列化:将磁盘文件中的二进制流还原成内存中的一个Java对象(ObjectInputStream)。

要想将一个自定义的Java对象是可序列化的,需要满足相应的要求:

  • 需要实现接口:Serializable
  • 给当前类提供全局常量:serialVersionUID
  • 除了当前类(Person)需要实现Serializable接口,还需要保证内部所有的属性也是可序列化的。(默认情况下,基本数据类型都是可序列化的)

注意ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量。

transient修饰符: 不可序列化的。

序列化对象:

public class Person implements Serializable {
    public static final long serialVersionUID = 48542L;
    private String name;
    private int age;
    private Account account;
    ....// get、set方法
}
class Account implements Serializable {
    private static final long serialVersionUID = 68547L;
    double money;
	....// get、set方法
}

序列化操作:

/** 序列化 */
@Test
public void testObjectOutputStream() {
    ObjectOutputStream objectOutputStream = null;
    try {
        objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("object.dat")));
        objectOutputStream.writeObject(new String("世界您好!"));
        objectOutputStream.flush();

        objectOutputStream.writeObject(new Person("Tom",20));
        objectOutputStream.flush();

        objectOutputStream.writeObject(new Person("Jerry",20,new Account(20000)));
        objectOutputStream.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (objectOutputStream != null) objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/** 反序列化 */
@Test
public void testObjectInputStream() {
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(new FileInputStream(new File("object.dat")));
        Object object = objectInputStream.readObject();
        String str = (String) object;
        Person person1 = (Person) objectInputStream.readObject();
        Person person2 = (Person) objectInputStream.readObject();
        System.out.println(str);// 世界您好!
        System.out.println(person1);// Person{name='Tom',age=20,account=null}
        System.out.println(person2);// Person{name='Jerry',age=20, account=Account{money=20000.0}}
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (objectInputStream != null) objectInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/BeautifulGirl230/p/14233189.html