SoFunction
Updated on 2025-05-13

How to use and precautions for automatically closing resources in try-with-resources in Java

Preface

In Java development, resource management is a very important topic, especially when dealing with operations such as files, database connections, network connections, etc. that require explicit release of resources. If the resource is not closed correctly, it may lead to memory leaks, file locking and other problems. Java provides a simple and efficient way to manage resources, i.e.try-with-resourcesgrammar.

1. Basic concepts

try-with-resources is a syntax introduced in Java 7 that allows one or more resources to be declared in a try block and automatically close these resources after the try block is executed. It simplifies resource management code and avoids manual writingtry-catch-finallytedious operations to close resources.

resourceRefers to the realizationInterface objects, such as file flow, database connection, etc. The resource that implements this interface can be called by calling itclose()Method to release.

2. Grammar

The syntax of try-with-resources is very simple and consists mainly of the following parts:

try (ResourceType resource = new ResourceType()) {
    // Code to use the resource} catch (ExceptionType e) {
    //Exception handling code}
  • Resource Statement:existtryThe resources declared in brackets will be automatically closed after the execution of the try block.
  • Automatically close: Resources must be realizedAutoCloseableOr its subinterfaceCloseable
  • Exception handling:Exception handling mechanism and ordinarytry-catchConsistent.

3. Usage method and code examples

Example 1: Use try-with-resources to read the file

Here is a simple example of reading the contents of a file:

import ;
import ;
import ;

public class TryWithResourcesExample {
    public static void main(String[] args) {
        String filePath = "";

        // Use try-with-resources to automatically manage resources        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = ()) != null) {
                (line);
            }
        } catch (IOException e) {
            ("File reading failed: " + ());
        }
    }
}

Analysis

  • existtryDeclared inBufferedReader, it is an implementationCloseableInterface resources.
  • No manual call required(), the resource will be automatically closed after the try block ends.

Example 2: Management of multiple resources

try-with-resources supports processing multiple resources simultaneously.

import ;
import ;
import ;

public class MultipleResourcesExample {
    public static void main(String[] args) {
        String inputFile = "";
        String outputFile = "";

        try (
            FileInputStream fis = new FileInputStream(inputFile);
            FileOutputStream fos = new FileOutputStream(outputFile)
        ) {
            int data;
            while ((data = ()) != -1) {
                (data);
            }
        } catch (IOException e) {
            ("File operation failed: " + ());
        }
    }
}

Analysis

  • At the same time, it declaredFileInputStreamandFileOutputStreamTwo resources.
  • After the try block ends, it will be in the order of resource declarations.Reverse orderClose the resource (that is, close it firstFileOutputStream, close againFileInputStream)。

4. Things to note

  • The resource must implement the AutoCloseable interface

    • Only realizedAutoCloseableThe interface class can only be used in try-with-resources.
    • Common implementation classes includeBufferedReaderFileInputStreamFileOutputStreamConnectionwait.
  • Resource scope

    • Resources declared in try brackets are scoped within try blocks and cannot be accessed externally.
  • Exception blocking problem

    • If an exception occurs in a try block and an exception occurs when closing the resource, Java will give priority to the exception in the try block, and the exception when closing the resource will be suppressed (suppressed).
    • Can be passed()Method to view suppressed exceptions.
  • compatibility

    • The try-with-resources syntax is supported since Java 7. If you need to use automatic shutdown resources in earlier versions, you must call them manuallyclose()method.
  • Custom Resources

    • Custom classes only need to be implementedAutoCloseableInterface and rewriteclose()Methods can be used in try-with-resources.

5. Pros and cons

advantage

  • Simplicity

    • Avoid manual writingfinallyBlocks to close resources, and the code is more concise and clear.
  • reliability

    • Automatically close resources, reducing the possibility of resource leakage.
  • Exception management

    • Built-in exception handling mechanism makes the code safer.
  • Code readability

    • Separate resource management logic from business logic to enhance the readability and maintainability of code.

shortcoming

  • Syntax Limitations

    • Only realizedAutoCloseableOnly try-with-resources can be used for the interface class.
  • Exception blocking

    • Although suppressed exceptions can be viewed, it can sometimes cause debugging difficulties.

6. Summary

try-with-resources is an efficient and concise resource management method provided by Java, which is especially suitable for handling resources that need to be explicitly closed (such as file flows, database connections, etc.). By automatically closing resources, it reduces the amount of code to manually manage resources while improving program reliability.

In actual development, it is recommended to use try-with-resources to deal with resource management issues, because it not only simplifies the code, but also greatly reduces the risk of resource leakage. In short, try-with-resources is a modern programming method that reflects Java's pursuit of code tidyness and robustness.

This is the article about automatically closing resources in Java. For more related Java try-with-resources, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!