In Java, theReader class provides a way to read character streams. Its close() method is used to close the stream and release any associated resources.
- If the stream is open, close() closes it and releases any associated resources.
- If the stream is already closed, calling close() has no effect.
- Any read or write operation attempted after closing the stream will throw an IOException.
Syntax
public abstract void close()
- Parameters: This method does not accept any parameters
- Return Type: This method does not return any value.
Examples of close() Method
Example 1: Reading Characters and Closing the Stream
Javaimportjava.io.*;classGFG{publicstaticvoidmain(String[]args){try{Stringstr="GeeksForGeeks";// Create a Reader instanceReaderreader=newStringReader(str);intch;// Read the first 5 charactersfor(inti=0;i<5;i++){ch=reader.read();System.out.println("Integer value of character read: "+ch);System.out.println("Actual character read: "+(char)ch);}// Close the streamreader.close();System.out.println("Stream Closed.");}catch(Exceptione){System.out.println(e);}}}OutputInteger value of character read: 71Actual character read: GInteger value of character read: 101Actual character read: eInteger value of character read: 101Actual character read: eInteger value o...
Explanation: The first 5 characters of the string "GeeksForGeeks" are read and printed. Calling close() releases the stream resources, marking the end of the reader’s usage.
Example 2: Performing Operations After Closing the Stream
Javaimportjava.io.*;classGFG{publicstaticvoidmain(String[]args){try{Stringstr="GeeksForGeeks";// Create a Reader instanceReaderreader=newStringReader(str);// Close the streamreader.close();System.out.println("Stream Closed.");// Attempt to check if the reader is readySystem.out.println("Is Reader ready to be read? "+reader.ready());}catch(Exceptione){System.out.println(e);}}}OutputStream Closed.java.io.IOException: Stream closed
Explanation:After calling close(), any attempt to read from or interact with the stream (e.g., ready()) results in an IOException.
Why Use close()?
- Prevents resource leaks in your program.
- Ensures that files or network streams are properly released.
- Mandatory in real-world applications to avoid memory and file descriptor exhaustion.
Note:Using try-with-resources in Java automatically calls close() on streams, making code safer and cleaner.
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java