Java.io.ObjectInputStream.readObject() 方法



描述

java.io.ObjectInputStream.readObject() 方法從 ObjectInputStream 讀取一個物件。物件的類、類的簽名以及類及其所有超類的非瞬態和非靜態欄位的值都會被讀取。可以使用 writeObject 和 readObject 方法覆蓋類的預設反序列化。此物件引用的物件會進行傳遞性讀取,以便透過 readObject 重建完整的等效物件圖。

當所有欄位以及它引用的物件都完全恢復時,根物件就會被完全還原。此時,物件驗證回撥將根據其註冊的優先順序按順序執行。回撥由物件(在其 readObject 特殊方法中)在它們分別恢復時註冊。

如果 InputStream 出現問題,或者不應該反序列化的類,則會丟擲異常。所有異常都會對 InputStream 造成致命影響,並將其置於不確定的狀態;呼叫方需要忽略或恢復流狀態。

宣告

以下是 java.io.ObjectInputStream.readObject() 方法的宣告。

public final Object readObject()

引數

返回值

此方法返回從流中讀取的物件。

異常

  • ClassNotFoundException − 無法找到序列化物件的類。

  • InvalidClassException − 序列化使用的類出現問題。

  • StreamCorruptedException − 流中的控制資訊不一致。

  • OptionalDataException − 流中找到原始資料而不是物件。

  • IOException − 任何常見的輸入/輸出相關異常。

示例

以下示例演示了 java.io.ObjectInputStream.readObject() 方法的用法。

package com.tutorialspoint;

import java.io.*;

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello World";
      byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeObject(s);
         oout.writeObject(b);
         oout.flush();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print an object and cast it as string
         System.out.println("" + (String) ois.readObject());

         // read and print an object and cast it as string
         byte[] read = (byte[]) ois.readObject();
         String s2 = new String(read);
         System.out.println("" + s2);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並執行以上程式,這將產生以下結果:

Hello World
example
java_io_objectinputstream.htm
廣告