The try-with-resources statement in Java is used to automatically manage and close resources such as files, streams, database connections, and sockets. It ensures that resources are closed after use, preventing memory leaks and reducing boilerplate code.
AutoCloseablefinally blocks for closing resourcesResources are declared inside the try() parentheses. When execution exits the block, Java automatically calls the close() method on each resource.
// Basic syntax of try-with-resources
try (ResourceType resource = new ResourceType()) {
System.out.println("Using the resource");
}
// Reading a file using try-with-resources
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example:
BufferedReader is created inside the try()finally block is requiredClick the buttons to see how Java handles resources in the console log below.
close() inside the try blockAutoCloseable