Closing Streams Safely
try-with-resources.
Closing Streams Safely is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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();The Old, Risky Way
You could call close() manually, but if an error happens before that line runs, close() is skipped and the resource leaks.
Putting close() in a finally block helps, but it is verbose and easy to get wrong.
BufferedReader br = null;
try {
br = new BufferedReader(
new InputStreamReader(System.in));
// ... use br ...
} finally {
if (br != null) br.close();
}try-with-resources
Java has a cleaner solution: try-with-resources. You declare the stream inside parentheses after try, and Java automatically closes it when the block ends — even if an error occurs.
No finally, no manual close(). This is the modern best practice.
try (BufferedReader br =
new BufferedReader(new InputStreamReader(System.in))) {
String line = br.readLine();
System.out.println(line);
}How It Works
Any resource declared in the try (...) parentheses must implement AutoCloseable. BufferedReader does, so Java calls its close() for you.
The closing happens after the block finishes, whether it ends normally or by an exception.
A Full Example
Here is a complete program using try-with-resources to read one line. The reader closes automatically at the end of the block.
It reads from System.in, so it waits for input and is not auto-runnable here.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(System.in))) {
String name = br.readLine();
System.out.println("Hi " + name);
}
}
}Runnable with StringReader
To prove try-with-resources works without keyboard input, here it reads from a StringReader. This is fully runnable.
After the block, the reader is closed automatically — you do not write any close() call.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader br =
new BufferedReader(new StringReader("done"))) {
System.out.println(br.readLine());
}
}
}Multiple Resources
You can declare several resources in one try, separated by semicolons. Java closes them all, in reverse order of declaration.
This is handy when you wrap multiple streams together.
try (InputStreamReader isr =
new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)) {
System.out.println(br.readLine());
}Catching IOException
Reading can throw IOException. You can add a catch to a try-with-resources block to handle it instead of declaring throws.
The resource still closes automatically before the catch runs.
try (BufferedReader br = new BufferedReader(
new InputStreamReader(System.in))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Read failed");
}Should You Close System.in?
One caution: closing a reader on System.in also closes System.in itself, and you cannot reopen it.
For short programs this is fine. But if you still need console input later, do not close that particular reader. Know what your stream wraps.
Best Practices
To handle streams safely:
- Prefer try-with-resources over manual
close(). - It auto-closes even when errors happen.
- Remember closing a
System.inreader closes standard input.
Clean resource handling prevents leaks and bugs.
Quick Check
Think about the main benefit of try-with-resources.
Recap
You learned why streams must be closed, the risky manual/finally approach, and the clean try-with-resources pattern that auto-closes AutoCloseable resources.
You can now read input with BufferedReader safely from start to finish.
Frequently asked questions
Is the “Closing Streams Safely” lesson free?
Yes — the full text of “Closing Streams Safely” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Closing Streams Safely”?
try-with-resources. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Closing Streams Safely” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why BufferedReader
- Reading Lines
- Parsing Numbers from Input
- Closing Streams Safely