ObjectInputStream close() method in Java with examples

The close() method of the ObjectInputStream class in Java closes the input stream.

Syntax:

public void close()

Parameters: This method does not accept any parameter.

Return Value: This method does not returns anything.

Below program illustrate the above method:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate 
// the above method
  
import java.io.*;
  
public class GFG {
  
    public static void main(String[] args) throws Exception
    {
  
        try {
            // Creates a new file
            // with an ObjectOutputStream
            FileOutputStream out
                = new FileOutputStream("gopal.txt");
            ObjectOutputStream out1
                = new ObjectOutputStream(out);
  
            // write in the file
            out1.writeUTF("Geeks for Geeks");
  
            // FLushes the stream
            out1.flush();
  
            // Create an ObjectInputStream
            // for the file we created before
            ObjectInputStream example
                = new ObjectInputStream(
                    new FileInputStream("gopal.txt"));
  
            // read from the stream
            for (int i = 0; i < example.available();) {
                System.out.println("" + (char)example.read());
            }
  
            // closes the stream
            System.out.println("\nClosing Stream...");
  
            example.close();
  
            // Stream closed
            System.out.println("Stream Closed.");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

chevron_right


Output:

Reference: https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#close()

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.