Java - ObjectInputStream close() method



Description

The Java ObjectInputStream close() method closes the input stream and releases associated system resources. Once closed, attempting to read from the stream throws an IOException.

Declaration

Following is the declaration for java.io.ObjectInputStream.close() method −

public void close()

Parameters

NA

Return Value

This method does not return a value.

Exception

IOException − If an I/O error has occurred.

Example - Usage of ObjectInputStream close() method

The following example shows the usage of Java ObjectInputStream close() method.

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUTF("Hello World");
         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());
         }

         // change line
         System.out.println();

         // close the stream
         System.out.println("Closing Stream...");
         ois.close();
         System.out.println("Stream Closed.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

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

Hello World
Closing Stream...
Stream Closed.

Example - Closing an ObjectInputStream After Reading an Object

The following example shows the usage of Java ObjectInputStream close() method. This example writes an object to a file, reads it using ObjectInputStream, and then closes the stream.

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

class Person implements Serializable {
   private static final long serialVersionUID = 1L;
   String name;
   int age;

   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }

   @Override
   public String toString() {
      return "Person{name='" + name + "', age=" + age + "}";
   }
}

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try {
         // Serialize object to file
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"));
         oos.writeObject(new Person("Alice", 30));
         oos.close();

         // Read object from file
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
         Person person = (Person) ois.readObject();
         System.out.println("Read Object: " + person);

         // Close the ObjectInputStream
         ois.close();

         // Trying to read again after closing
         System.out.println("Trying to read again...");
         ois.readObject(); // This will throw an IOException

      } catch (IOException | ClassNotFoundException e) {
         System.out.println("Exception: " + e.getMessage());
      }
   }
}

Output

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

Read Object: Person{name='Alice', age=30}
Trying to read again...
Exception: Stream Closed

Explanation

  • Writes a Person object to a file (person.dat).

  • Reads the object using ObjectInputStream.

  • Closes the stream using ois.close().

  • Attempts to read again after closing, which throws an IOException: Stream Closed.

Example - Closing ObjectInputStream in a Try-With-Resources Block

The following example shows the usage of Java ObjectInputStream close() method. This example demonstrates how close() is automatically called when using try-with-resources.

ObjectInputStreamDemo.java

package com.tutorialspoint;

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

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat"))) {
         oos.writeObject("Hello, World!");
      } catch (IOException e) {
         e.printStackTrace();
      }

      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.dat"))) {
         String message = (String) ois.readObject();
         System.out.println("Read Object: " + message);
      } catch (IOException | ClassNotFoundException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Read Object: Hello, World!

Explanation

  • Writes a String object to data.dat.

  • Uses try-with-resources for ObjectInputStream, ensuring close() is called automatically.

  • Reads the object and prints it.

  • No need for an explicit close() call, as try-with-resources automatically handles it.

java_io_objectinputstream.htm
Advertisements