Java:Java Try-With-Resources and File I/O (AutoCloseable)
Java•File Handling & RAII

Java Try-With-Resources and File I/O (AutoCloseable)

Any object implementing java.lang.AutoCloseable can be managed automatically by try-with-resources.

Syntax

try (BufferedReader reader = new BufferedReader(...)) { // read }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
try (resource)StatementAutomatically invokes close() on resource exit.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String logData = "INIT: Cluster Started\nINFO: DB Pool Ready\nOK: Health Check Passed";

        // Try-with-resources guarantees streams are closed automatically
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new ByteArrayInputStream(logData.getBytes())))) {

            String line;
            int count = 1;
            while ((line = reader.readLine()) != null) {
                System.out.println("Line #" + count++ + ": " + line);
            }
        } catch (IOException e) {
            System.err.println("I/O Error: " + e.getMessage());
        }

        System.out.println("[SUCCESS] Resources closed automatically.");
    }
}
Expected Output:
Line #1: INIT: Cluster Started
Line #2: INFO: DB Pool Ready
Line #3: OK: Health Check Passed
[SUCCESS] Resources closed automatically.

How It Works: Step-by-Step

  • Lines 11-13: Declares BufferedReader inside try() parentheses.
  • Lines 16-19: Reads lines sequentially until EOF (null).
  • Line 23: Reader is closed automatically upon exiting block.

Key Concepts

  • try-with-resources replaces cumbersome nested finally blocks.
  • Multiple resources can be declared in try separated by semicolons.
  • Resources are closed in reverse order of their declaration.

Common Mistake: Manually closing resources inside try instead of using try-with-resources

If an error occurs before close(), the file handle or socket leaks.

❌ Incorrect
BufferedReader br = new BufferedReader(...);
br.close(); // Skipped if exception thrown above!
✅ Correct
try (BufferedReader br = new BufferedReader(...)) { /* Safe */ }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler