Java ObjectInputStream.close()

Syntax

ObjectInputStream.close() has the following syntax.

public void close()  throws IOException

Example

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


//  w  ww.  j a v a 2 s  .  c o  m

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 {

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

    // write something in the file
    oout.writeUTF("Hello World from java2s.com");
    oout.flush();

    // create an ObjectInputStream for the file we created before
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
        "test.txt"));

    // read from the stream
    for (int i = 0; i < ois.available();) {
      System.out.print((char) ois.read());
    }

    ois.close();

  }
}

The code above generates the following result.