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


Java Java.io.ObjectOutputStream enableReplaceObject()用法及代碼示例


描述

這個java.io.ObjectOutputStream.enableReplaceObject(boolean enable)方法使流能夠替換流中的對象。啟用後,將為每個正在序列化的對象調用 replaceObject 方法。

如果 enable 為 true,並且安裝了安全管理器,則此方法首先使用 SerializablePermission("enableSubstitution") 權限調用安全管理器的 checkPermission 方法,以確保可以啟用流來替換流中的對象。

聲明

以下是聲明java.io.ObjectOutputStream.enableReplaceObject()方法。

protected boolean enableReplaceObject(boolean enable)

參數

enable- 啟用對象替換的布爾參數。

返回值

在調用此方法之前,此方法將返回先前的設置。

異常

SecurityException− 如果安全管理器存在且其 checkPermission 方法拒絕啟用流替換流中的對象。

示例

下麵的例子展示了使用java.io.ObjectOutputStream.enableReplaceObject()方法。

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo extends ObjectOutputStream {

   public ObjectOutputStreamDemo(OutputStream out) throws IOException {
      super(out);
   }

   public static void main(String[] args) {
      int i = 319874;
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStreamDemo oout = new ObjectOutputStreamDemo(out);

         // enable replacing objects and return the previous setting
         System.out.println("" + oout.enableReplaceObject(true));

         // write something in the file
         oout.writeInt(i);
         oout.writeInt(1653984);
         oout.flush();

         // 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 an int
         System.out.println("" + ois.readInt());

         // read and print an int
         System.out.println("" + ois.readInt());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

false
319874
1653984

相關用法


注:本文由純淨天空篩選整理自 Java.io.ObjectOutputStream enableReplaceObject() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。