當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java ObjectInputStream readObject()用法及代碼示例

ObjectInputStream類readObject()方法

  • readObject() 方法可在java.io包。
  • readObject() 方法用於從這個 ObjectInputStream 中讀取一個對象,並從類的對象、類的簽名、類的非靜態字段的值等方麵讀取該對象。
  • readObject() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • readObject() 方法可能會在讀取對象時拋出異常。
    • 類未找到異常:當序列化對象類不存在時,可能會拋出此異常。
    • 無效類異常:當序列化使用的無效類時,可能會拋出此異常。
    • 流損壞異常:流中的操作信息不一致時可能會拋出此異常。
    • IOException:在執行時遇到任何輸入/輸出錯誤時可能會拋出此異常。

用法:

    public Object readObject();

參數:

  • 它不接受任何參數。

返回值:

該方法的返回類型是Object,它返回從 ObjectInputStream 讀取的 Object。

例:

// Java program to demonstrate the example 
// of Object readObject() method of ObjectInputStream

import java.io.*;

public class ReadObjectClass {
 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and FileOutputStream
  FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
  ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
  FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
  ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);

  // By using writeObject() method is to
  // write object to Serialized class
  obj_out_stm.writeObject(new DefaultObjectClass());
  obj_out_stm.flush();

  // By using readObject() method is to
  // read an object from the Serialized class
  DefaultObjectClass def_obj = (DefaultObjectClass) obj_in_stm.readObject();

  // Using both readObject and defaultReadObject(); 
  System.out.println("obj_in_stm.readObject():" + def_obj.str);
 }

 static class DefaultObjectClass implements Serializable {
  String str = "Java World";
  private void readObject(ObjectInputStream obj_stm) throws IOException, ClassNotFoundException {
   // By using defaultReadObject() method is 
   // to read non-static fields of the present 
   // class from the ObjectInputStream
   obj_stm.defaultReadObject();
  }
 }
}

輸出

obj_in_stm.readObject():Java World


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java ObjectInputStream readObject() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。