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

Try-With-Resources and readLine Loops

Combine try-with-resources with readLine loops to ensure proper closure of file streams and prevent resource leaks.

Try-With-Resources and readLine Loops

You'll learn how to combine automatic resource management with line-by-line file reading to write clean, leak-free code.

When you read text files line-by-line using BufferedReader and readLine, you're working with a resource that must be closed. Forgetting to close the reader leaves file handles open, potentially exhausting system resources. This is where try-with-resources shines: it automatically closes the BufferedReader for you, even if exceptions occur.

The Perfect Pairing

Think of try-with-resources as a safety net under a tightrope walker (your file-reading loop). Even if something goes wrong mid-performance (an exception), the net catches you and ensures cleanup happens.

Here's the pattern:

try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // Process each line
        System.out.println(line);
    }
} catch (IOException e) {
    System.err.println("Error reading file: " + e.getMessage());
}
// reader is automatically closed here, no matter what

How It Works

  1. The BufferedReader is declared in the try-with-resources parentheses
  2. The while loop calls readLine() until it returns null (end-of-file)
  3. When the try block ends—whether normally or via exception—Java automatically calls reader.close()
  4. You avoid resource leaks without writing manual cleanup code

This pattern is the standard way to read text files in Java. It's safe, concise, and makes your intentions crystal clear.

Key Takeaway: Always wrap BufferedReader and readLine() loops in try-with-resources to guarantee proper stream closure and prevent resource leaks—Java handles the cleanup automatically.