The close() Method and Stream Lifecycle
You'll learn why closing streams is non-negotiable and what happens when you forget.
Why Closing Matters
When you open a stream (like FileInputStream or FileOutputStream), Java allocates system resources—file handles, memory buffers, and sometimes network connections. These resources are limited. If you don't explicitly close your streams, those resources remain locked even after you're done reading or writing.
Think of it like borrowing a book from a library. If you never return it, nobody else can borrow it, and eventually the library runs out of books. Similarly, your operating system has a finite number of file handles. Leave too many streams open, and your application (or even your entire system) can't open new files.
The Resource Release Contract
Every InputStream and OutputStream has a close() method inherited from their parent classes. Calling close():
- Releases system resources (file handles, sockets)
- Flushes buffered data (writes any pending bytes to disk)
- Marks the stream as closed (further operations throw exceptions)
FileInputStream in = new FileInputStream("data.txt");
// ... read data ...
in.close(); // Release the file handle
What Happens When You Don't Close
Without closing:
- File locks persist, preventing deletion or modification by other processes
- Memory leaks accumulate as buffers aren't freed
- "Too many open files" errors crash your application
- Data loss if buffered writes never flush
Always close streams, preferably using try-with-resources (coming later in this course), which automates cleanup.
Key Takeaway:
Always call close() on streams to release system resources—failing to do so causes resource exhaustion, file locks, and potential data loss.