How do I close a file automatically using try-with-resources in Java?

Use a try-with-resources statement to close a file reader automatically. Java closes the reader when execution leaves the try block, even if reading fails.

In this example, you will open a UTF-8 text file with a BufferedReader and print it one line at a time.

Source code

Save the following code as TryWithResourcesExample.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TryWithResourcesExample {
    void main() {
        Path path = Path.of("greeting.txt");

        try (BufferedReader reader =
                Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;

            while ((line = reader.readLine()) != null) {
                IO.println(line);
            }
        } catch (IOException exception) {
            System.err.println(
                    "Could not open, read, or close the file: "
                            + exception.getMessage());
        }
    }
}

Explanation

The declaration inside the parentheses after try opens the file and creates a BufferedReader:

try (BufferedReader reader =
        Files.newBufferedReader(path, StandardCharsets.UTF_8)) {

A BufferedReader implements AutoCloseable, so Java can call its close() method automatically. Closing the reader also closes the underlying file resource.

Inside the block, readLine() returns the next line without its line separator. It returns null when there are no more lines. The while condition assigns each result to line and checks whether it is null. A blank line returns an empty string, so it is still printed.

When the loop ends, Java closes the reader. If reading throws an exception, Java still attempts to close the reader before running the catch block. You do not need to call close() yourself or add a finally block for cleanup.

Run the example

Reuse greeting.txt from the previous example, or create it as a UTF-8 file with these contents:

Hello, Java!
Learning Java one snippet at a time.

From the directory containing both files, compile and run the program:

javac TryWithResourcesExample.java
java TryWithResourcesExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use try-with-resources when you open a reader or writer yourself. Convenience methods such as Files.readString() and Files.writeString() already manage the file resource for you.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.