34.4 对象流 ObjectOutputStream ObjectInputStream

* 对象操作流:可以用于读写任意类型的对象
* ObjectOutputStream
*    writeObject
*    ObjectOutputStream(OutputStream out)
* ObjectInputStream
*    readObject
*    ObjectInputStream(InputStream in)
*
* 注意:
* 使用对象输出流写出对象,只能使用对象输入流来读取对象
* 只能将支持 java.io.Serializable 接口的对象写入流中

Demo

public class O1_流对象概述 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        writeMethod();
        //使用对象输出流写出对象,只能使用对象输入流来读取对象
        readMethod();


    }

    private static void readMethod() throws IOException, ClassNotFoundException {
        //创建输入流对象(读入数据)
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oo.txt"));

        //读取数据
        String s = (String)ois.readObject();
        System.out.println(s);

        int i = ois.readInt();
        System.out.println(i);

        Date d = (Date)ois.readObject();
        System.out.println(d);

        //释放资源
        ois.close();
    }

    //创建输出流对象(写出数据)
    private static void writeMethod() throws IOException {
        //创建输出流对象(写出数据)
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oo.txt"));

        //写数据
        oos.writeObject("hello");//写字符串对象
        oos.writeInt(123);
        oos.writeObject(new Date());//写日期对象

        //释放资源
        oos.close();
    }
}

输出:

使用对象输出流写出对象,只能使用对象输入流来读取对象。写入的oo.txt文件用文本编辑器不能查看,只能用对象流查看。(序列化与反序列化)

原文地址:https://www.cnblogs.com/longesang/p/11320118.html