0Pricing
Java Academy · Lesson

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

  1. Why BufferedReader
  2. Reading Lines
  3. Parsing Numbers from Input
  4. Closing Streams Safely
← Back to Java Academy