Java.io.ObjectOutputStream.writeObject() 方法



描述

java.io.ObjectOutputStream.writeObject(Object obj) 方法將指定的物件寫入 ObjectOutputStream。物件的類、類的簽名以及類及其所有超型別的非瞬態和非靜態欄位的值將被寫入。可以使用 writeObject 和 readObject 方法覆蓋類的預設序列化。此物件引用的物件將被傳遞地寫入,以便可以透過 ObjectInputStream 重建物件的完整等效圖形。

宣告

以下是 java.io.ObjectOutputStream.writeObject() 方法的宣告。

public final void writeObject(Object obj)

引數

obj − 要寫入的物件。

返回值

此方法不返回值。

異常

  • InvalidClassException − 序列化使用的類存在問題。

  • NotSerializableException − 要序列化的某些物件未實現 java.io.Serializable 介面。

  • IOException − 底層 OutputStream 丟擲的任何異常。

示例

以下示例演示了 java.io.ObjectOutputStream.writeObject() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello world!";
      int i = 897648764;
      
      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(i);

         // close the stream
         oout.close();

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

         // read and print what we wrote before
         System.out.println("" + (String) ois.readObject());
         System.out.println("" + ois.readObject());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello world!
897648764
java_io_objectoutputstream.htm
廣告

© . All rights reserved.