Sobes.tech
Junior — Middle

How can automatic resource closing be managed in Java without using try-with-resources?

sobes.tech AI

Answer from AI

Without using the try-with-resources statement in Java, automatic resource management can be handled with a try-finally block. In the try block, the resource is created and used, and in the finally block, it is closed to ensure resources are released even if an exception occurs.

Example:

InputStream input = null;
try {
    input = new FileInputStream("file.txt");
    // work with the resource
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Thus, the finally block ensures the resource is closed regardless of whether an exception occurred or not. This method was standard before the introduction of try-with-resources in Java 7.

How can automatic resource closing be managed in Java… - sobes.tech