Java.io.ObjectOutputStream useProtocolVersion() Method



Description

The java.io.ObjectOutputStream.useProtocolVersion(int version) method specifies stream protocol version to use when writing the stream.

This routine provides a hook to enable the current version of Serialization to write in a format that is backwards compatible to a previous version of the stream format.

Declaration

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

public void useProtocolVersion(int version)

Parameters

version − use ProtocolVersion from java.io.ObjectStreamConstants.

Return Value

This method does not return a value.

Exception

  • IllegalStateException − If called after any objects have been serialized.

  • IllegalArgumentException − If invalid version is passed in.

  • IOException − If I/O errors occur

Example

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

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      Object s = "Hello World!";
      Object s2 = "Bye World!";
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // change protocol version
         oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_1);

         // write something in the file
         oout.writeObject(s);
         oout.writeObject(s2);

         // 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 a string
         System.out.println("" + (String) ois.readObject());
         System.out.println("" + (String) ois.readObject());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello World!
Bye World!
java_io_objectoutputstream.htm
Advertisements