ObjectInputStream readUnshared() Method in Java

In the given tutorial, we are going to learn neatly about readUnshared() method of ObjectInputStream class in Java.

readUnshared() in Java

The readUnshared() method is zero argument type method which returns a reference to a deserialized object. This method would read in an “unshared” object, which means the one that should only appear once in the ObjectInputStream. Unlike to readObject, this method prevents subsequent calls to readObject and readUnshared from reoccurring more back references to the deserialized instance obtained through the given call.

Also read: InputStream skip() Method in Java

Declaration :
The declaration for java.io.ObjectInputStream.readUnshared() method is :

public Object readUnshared()

Exception :
This method can throw following exceptions :

  • ClassNotFoundException : When class of an object to deserialize is unable to found.
  • ObjectStreamException : When object to deserialize already appears in stream.
  • OptionalDataException : When primitive data is next in stream.
  • StreamCurruptedException : When control information in the stream is uncertain.
  • IOException : When an I/O error occurs during deserialization.

Example :
To understand the usage of java.io.ObjectInputStream.readUnshared() method, we should see the following example :

package java;
import java.io.*;

public class Example
{
 public static void main(String[] args)
  {
   String msg = "Welcome to CodeSpeedy...!!!";
   
   try
   {
    //We are creating a new file by using ObjectOutputStream
    FileOutputStream fout = new FileOutputStream("demo.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fout);

    //We are writing the content in file
    oos.writeUnshared(msg);
    oos.flush();

    //We are creating an ObjectInputStream for demo.txt
    ObjectInputStream ois = new ObjectInputStream( new FileInputStream("demo.txt"));

    //Reading and printing the unshared object
    System.out.println(ois.readUnshared());
    }
   catch (Exception e)
    {
     e.printStackTrace();
    }
  }
}

The output of the given program will be :

Welcome to CodeSpeedy...!!!

In this program, we have created a new file by using FileOutputStream and ObjectOutputStream class object. Then we have added the content in the file using writeUnshared(*) method by giving String as an argument. After creating an ObjectInputStream object for the file we created before, we are reading and printing the unshared object by using readUnshared() method.

Leave a Reply

Your email address will not be published. Required fields are marked *