Reader close() method in Java with Examples
Last Updated :
24 Oct, 2025
In Java, the Reader 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
Java
import java.io.*;
class GFG {
public static void main(String[] args){
try {
String str = "GeeksForGeeks";
// Create a Reader instance
Reader reader = new StringReader(str);
int ch;
// Read the first 5 characters
for (int i = 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 stream
reader.close();
System.out.println("Stream Closed.");
}
catch (Exception e) {
System.out.println(e);
}
}
}
OutputInteger value of character read: 71
Actual character read: G
Integer value of character read: 101
Actual character read: e
Integer value of character read: 101
Actual character read: e
Integer 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
Java
import java.io.*;
class GFG{
public static void main(String[] args){
try {
String str = "GeeksForGeeks";
// Create a Reader instance
Reader reader = new StringReader(str);
// Close the stream
reader.close();
System.out.println("Stream Closed.");
// Attempt to check if the reader is ready
System.out.println(
"Is Reader ready to be read? "
+ reader.ready());
}
catch (Exception e) {
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