1. 程式人生 > 實用技巧 >Java IO流 ObjectOutputStream、ObjectInputStream的基本使用

Java IO流 ObjectOutputStream、ObjectInputStream的基本使用

            ObjectOutputStream、ObjectInputStream的使用

  ObjectOutputStream將Java物件的原始資料型別和圖形寫入OutputStream。可以使用ObjectInputStream讀取

(重構)物件。 可以通過使用流的檔案來實現物件的持久儲存如果流是網路套接字流,則可以在另一個主機上或另

一個程序中重構物件,只有支援java.io.Serializable介面的物件才能寫入流中。方法readObject用於從流中讀取物件

應使用Java的安全鑄造來獲得所需的型別。 在Java中,字串和陣列是物件,在序列化過程中被視為物件。 讀取時

需要將其轉換為預期型別。

  ObjectInputStream反序列化先前使用ObjectOutputStream編寫的原始資料和物件,ObjectOutputStream和

ObjectInputStream可以分別為與FileOutputStream和FileInputStream一起使用的物件圖提供永續性儲存的應用程

序。 ObjectInputStream用於恢復先前序列化的物件。 其他用途包括使用套接字流在主機之間傳遞物件,或者在遠端

通訊系統中進行封送和解組引數和引數。ObjectInputStream確保從流中建立的圖中的所有物件的型別與Java虛擬機器

中存在的類匹配。 根據需要使用標準機制載入類。只能從流中讀取支援java.io.Serializable或java.io.Externalizable

介面的物件。方法readObject用於從流中讀取物件。 應使用Java的安全鑄造來獲得所需的型別。 在Java中,字串

和陣列是物件,在序列化過程中被視為物件。 讀取時,需要將其轉換為預期型別。可以使用DataInput上的適當方法

從流中讀取原始資料型別。

  以下例子是ObjectOutputStream和ObjectInputStream的簡單使用。首先是通過物件輸出流ObjectOutputStream

在指定檔案寫入資料物件,然後再通過ObjectInputStream進行讀取。

FileInputStream的使用可參考https://www.cnblogs.com/jhtian/p/14110083.html

測試程式碼:

package com.tianjh.io;

import java.io.*;

/**
 * Created on 2020/12/10
 * $ObjectStreamDemo 類必須實現Serializable接口才可以被序列化
 * 否則會拋NotSerializableException異常
 *
 * @author tianjh
 */
public class ObjectStreamDemo implements Serializable {
    private final String name;
    private final int id;

    public ObjectStreamDemo(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return "ObjectStreamDemo{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }

    public static void main(String[] args) {
        try {
            // 指定檔案
            String sourceFile = "D:/ObjectStream.txt";
            /*
             * An ObjectOutputStream writes primitive data types and graphs of Java objects
             * to an OutputStream.  The objects can be read (reconstituted) using an
             * ObjectInputStream.  Persistent storage of objects can be accomplished by
             * using a file for the stream.  If the stream is a network socket stream, the
             * objects can be reconstituted on another host or in another process.
             *
             * ObjectOutputStream將Java物件的原始資料型別和圖形寫入OutputStream。
             * 可以使用ObjectInputStream讀取(重構)物件。 可以通過使用流的檔案來實現物件的持久儲存
             * 如果流是網路套接字流,則可以在另一個主機上或另一個程序中重構物件,只有支援java.io.Serializable
             * 介面的物件才能寫入流中
             */
            FileOutputStream fos = new FileOutputStream(sourceFile);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            // 將指定的物件寫入ObjectOutputStream
            oos.writeObject(new ObjectStreamDemo("小明", 1));
            oos.writeObject(new ObjectStreamDemo("小王", 2));
            // 關閉相關流
            oos.close();
            fos.close();

            /*
             * An ObjectInputStream deserializes primitive data and objects previously
             * written using an ObjectOutputStream.
             *
             * ObjectInputStream反序列化先前使用ObjectOutputStream編寫的原始資料和物件
             */
            FileInputStream fis = new FileInputStream(sourceFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            // 從ObjectInputStream讀取一個物件
            ObjectStreamDemo e1 = (ObjectStreamDemo) ois.readObject();
            ObjectStreamDemo e2 = (ObjectStreamDemo) ois.readObject();

            System.out.println(e1.toString());
            // expected output: ObjectStreamDemo{name='小明', id=1}
            System.out.println(e2.toString());
            // expected output: ObjectStreamDemo{name='小王', id=2}
            // 關閉相關流
            ois.close();
            fis.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

輸出結果: