Junior — Middle
How to implement automatic resource closing using try-with-resources construct?
sobes.tech AI
Answer from AI
In Java, the try-with-resources statement is used for automatically closing resources that implement the AutoCloseable interface (such as input/output streams, database connections). Resources declared in the parentheses after the try keyword are automatically closed after the block finishes, even if an exception occurs inside the block.
Example:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
// reader is automatically closed here
This eliminates the need to explicitly call close() and reduces the risk of resource leaks.