Java.io.ObjectInputStream readObjectOverride() 方法



描述

java.io.ObjectInputStream.readObjectOverride() 方法由使用受保護的無引數建構函式構建 ObjectOutputStream 的 ObjectOutputStream 可信子類呼叫。子類應提供一個帶有“final”修飾符的覆蓋方法。

宣告

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

protected Object readObjectOverride()

引數

返回值

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

異常

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

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

  • IOException − 如果在從底層流讀取時發生 I/O 錯誤

示例

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

package com.tutorialspoint;

import java.io.*;

public class ObjectInputStreamDemo extends ObjectInputStream{

   public ObjectInputStreamDemo(InputStream in) throws IOException {
      super(in);
    }
    
   public static void main(String[] args) {
      String s = "Hello World";
      
      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.flush();

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

         // read and print an object and cast it as string
         System.out.println("" + (String)ois.readObjectOverride());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

null
java_io_objectinputstream.htm
廣告