try-with-resources Statement in Java


The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be used as a resource.

Source Code

try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Use try-with-resources for better resource management and to automatically close resources, reducing the risk of resource leaks.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments