Java.io.ObjectOutputStream.writeUnshared() 方法



描述

java.io.ObjectOutputStream.writeUnshared(Object obj) 方法將“未共享”物件寫入 ObjectOutputStream。此方法與 writeObject 相同,只是它始終將給定物件作為流中一個新的、唯一的物件寫入(而不是指向先前序列化例項的反向引用)。具體來說 -

  • 透過 writeUnshared 寫入的物件始終以與新出現物件(尚未寫入流的物件)相同的方式序列化,無論該物件是否之前已被寫入。

  • 如果使用 writeObject 寫入之前已使用 writeUnshared 寫入的物件,則先前 writeUnshared 操作將被視為對單獨物件進行寫入。換句話說,ObjectOutputStream 永遠不會生成指向由對 writeUnshared 的呼叫寫入的物件資料的反向引用。

雖然透過 writeUnshared 寫入物件本身並不能保證在反序列化時對該物件的唯一引用,但它允許在流中多次定義單個物件,以便接收方對 readUnshared 的多次呼叫不會發生衝突。請注意,上述規則僅適用於使用 writeUnshared 寫入的基本級物件,而不適用於要序列化的物件圖中任何傳遞引用子物件。

覆蓋此方法的 ObjectOutputStream 子類只能在擁有“enableSubclassImplementation”SerializablePermission 的安全上下文中構造;任何在沒有此許可權的情況下例項化此類子類的嘗試都將導致丟擲 SecurityException。

宣告

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

public void writeUnshared(Object obj)

引數

obj - 要寫入流的物件。

返回值

此方法不返回值。

異常

  • NotSerializableException - 如果要序列化的圖中的物件未實現 Serializable 介面。

  • InvalidClassException - 如果要序列化的物件的類存在問題。

  • IOException - 如果在序列化期間發生 I/O 錯誤。

示例

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

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      Object s = "Hello World!";
      Object i = 1974;
      
      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.writeUnshared(s);
         oout.writeUnshared(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("" + ois.readUnshared());
         System.out.println("" + ois.readUnshared());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello World!
1974
java_io_objectoutputstream.htm
廣告