Java ObjectInputStream .readUnshared ()

Syntax

ObjectInputStream.readUnshared() has the following syntax.

public Object readUnshared()   throws IOException ,    ClassNotFoundException

Example

In the following code shows how to use ObjectInputStream.readUnshared() method.


//from   ww w  .ja  v  a 2 s  .c  om


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {

  public static void main(String[] args) throws Exception {
    String s = "Hello World from java2s.com";

    FileOutputStream out = new FileOutputStream("test.txt");
    ObjectOutputStream oout = new ObjectOutputStream(out);

    // write something in the file
    oout.writeUnshared(s);
    oout.flush();
    oout.close();
    // create an ObjectInputStream for the file we created before
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        "test.txt"));

    // read and print the unshared object
    System.out.println(ois.readUnshared());
    ois.close();
  }
}

The code above generates the following result.