Java try-with-resources

java

The try-with-resources statement is a try statement that declares one or more resources, which are objects that implement the AutoCloseable interface. These resources are automatically closed when the try statement completes, regardless of whether the try statement completes normally or abruptly.

The try-with-resources statement is useful for working with resources that need to be closed, such as input and output streams, database connections, and network sockets. It ensures that the resources are properly closed, even if an exception is thrown during the try block.

Here is an example of using the try-with-resources statement to read from a file:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

In this example, the BufferedReader object is declared as a resource and is automatically closed when the try statement finishes.

Using the try-with-resources statement can help you ensure that your resources are properly closed, even if an exception is thrown. It can also make your code more concise and easier to read.

Note that you can declare multiple resources in a try-with-resources statement, separated by a semicolon. The resources will be closed in the opposite order that they were declared.

Note that you can use multiple resources in a single try-with-resources statement by separating them with a semicolon. For example:

try (BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("file2.txt"))) {
    // code that uses br and bw
} catch (IOException e) {
    e.printStackTrace();
}