Closing Streams Safely
try-with-resources.
Why Close Streams
Streams like BufferedReader hold onto system resources — file handles, memory buffers, connections. If you never close them, those resources can leak.
Closing a stream frees what it holds and flushes any pending data. This lesson shows how to do it safely.
The close Method
Every reader has a close() method. Calling it releases the resource.
For a BufferedReader wrapping System.in, closing also closes the underlying streams it wraps.
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
// ... use br ...
br.close();All lessons in this course
- Why BufferedReader
- Reading Lines
- Parsing Numbers from Input
- Closing Streams Safely