// Created on savesnippets.com ยท https://savesnippets.com/ZzfKbktx26OAck 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 } } }