Java.io.ObjectOutputStream enableReplaceObject() Method



Description

The java.io.ObjectOutputStream.enableReplaceObject(boolean enable) method enables the stream to do replacement of objects in the stream. When enabled, the replaceObject method is called for every object being serialized.

If enable is true, and there is a security manager installed, this method first calls the security manager's checkPermission method with a SerializablePermission("enableSubstitution") permission to ensure it's ok to enable the stream to do replacement of objects in the stream.

Declaration

Following is the declaration for java.io.ObjectOutputStream.enableReplaceObject() method.

protected boolean enableReplaceObject(boolean enable)

Parameters

enable − boolean parameter to enable replacement of objects.

Return Value

This method returns the previous setting before this method was invoked.

Exception

SecurityException − If a security manager exists and its checkPermission method denies enabling the stream to do replacement of objects in the stream.

Example

The following example shows the usage of java.io.ObjectOutputStream.enableReplaceObject() method.

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();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

false
319874
1653984
java_io_objectoutputstream.htm
Advertisements