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
}
}
}
Create a free account and build your private vault. Share publicly whenever you want.