Course contentsShow
← Java
Lesson 1966 of 2,87040. File I/O: Character StreamsFree lesson

Closing Readers and Writers: Resource Management

Understanding the importance of closing character streams and how close() differs from flush().

Closing Readers and Writers: Resource Management

You'll learn why properly closing character streams is essential and how close() differs from flush() in resource management.

Why Closing Matters

Just like you learned with byte streams, character streams must be closed to prevent resource leaks. When you open a Reader or Writer, the JVM allocates system resources—file handles, memory buffers, and possibly encoding/decoding structures. Failing to close these streams leaves these resources locked, potentially preventing other programs (or even your own code) from accessing the same file.

The close() Method

The close() method releases all system resources associated with the stream. Once closed, you cannot read from or write to that stream again—attempting to do so throws an IOException.

Reader reader = new FileReader("data.txt");
// ... read operations ...
reader.close(); // Must close to release the file handle

close() vs flush()

Here's the crucial difference:

  • flush() writes any buffered data to the underlying destination but keeps the stream open for more operations
  • close() automatically calls flush() first, then releases all resources and makes the stream unusable

Think of it like a pen and notebook: flush() is making sure your ink reaches the paper, while close() is putting the cap on the pen and closing the notebook for good.

Best Practice: Try-With-Resources

Always use try-with-resources for automatic closing:

try (Reader reader = new FileReader("input.txt")) {
    // read operations
} // Automatically closes, even if exceptions occur

Key Takeaway: Always close Reader and Writer instances to release system resources; close() automatically flushes and then frees the stream, while flush() only writes buffered data without closing. Use try-with-resources for safe, automatic resource management.