Java

try-with-resources

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
For any `AutoCloseable` (files, streams, DB connections, locks), declare it in `try(...)` and Java auto-calls `close()` even on exception. Replaces error-prone `try / finally` blocks.
Java
Raw
import java.io.*;
import java.nio.file.*;

class Demo {
    String readFirstLine(String path) throws IOException {
        try (BufferedReader r = Files.newBufferedReader(Path.of(path))) {
            return r.readLine();
        }    // r.close() automatically — even if readLine throws
    }

    // Multiple resources — closed in reverse declaration order
    void copyFile(String src, String dst) throws IOException {
        try (var in  = Files.newInputStream(Path.of(src));
             var out = Files.newOutputStream(Path.of(dst))) {
            in.transferTo(out);
        }
    }

    // Java 9+ — pre-existing AutoCloseable variable can be used in try
    void example() throws IOException {
        var conn = Files.newBufferedReader(Path.of("file.txt"));
        try (conn) {                              // not `try (var x = conn)`
            // use conn
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.