Home  >  Article  >  Java  >  How to gracefully close resources using try-with-resources in Java 7

How to gracefully close resources using try-with-resources in Java 7

WBOY
WBOYOriginal
2023-07-29 10:09:231599browse

How to use try-with-resources to gracefully close resources in Java 7

In Java, we often need to use some resources, such as files, network connections, database connections, etc. After using these resources, in order to release the resources and avoid memory leaks, we need to explicitly close these resources in the program. In Java 7, a new syntactic sugar - try-with-resources - is introduced, allowing us to close resources more gracefully.

Before Java 7, we usually used try-catch-finally to close resources. For example, when we read a file, the code may look like this:

FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
    // 读取文件的操作
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This method seems more cumbersome and requires writing additional code to handle the closing of the resource, and an exception may occur causing the resource to be no longer available. timely closure.

In Java 7, we can use the try-with-resources statement to close resources more concisely. Using try-with-resources, we can put the close operation in the brackets of the try statement, and Java will automatically close the resource at the end of the try statement. For example, the above code can be rewritten as:

try (FileInputStream fis = new FileInputStream("file.txt")) {
    // 读取文件的操作
} catch (IOException e) {
    e.printStackTrace();
}

In the above code, we use try-with-resources to declare a FileInputStream object. When the try statement ends, Java will automatically call the close method of FileInputStream to close the resource. . If an exception occurs in the try statement block, the catch statement will catch and handle the exception.

try-with-resources can also declare multiple resources at the same time, and they will be closed in sequence in the order of declaration. For example, we read the contents of two files at the same time:

try (FileInputStream fis1 = new FileInputStream("file1.txt");
    FileInputStream fis2 = new FileInputStream("file2.txt")) {
    // 读取文件的操作
} catch (IOException e) {
    e.printStackTrace();
}

In the above code, we use semicolons to separate the declarations of multiple resources, and they will be closed one after another at the end of the try statement.

In addition, we can also use custom classes to automatically close resources. You only need to implement the AutoCloseable interface in your custom class and override the close method. For example, we create a custom network connection class:

public class MyConnection implements AutoCloseable {
    public MyConnection() {
        // 进行连接的操作
    }
    
    // 执行一些操作
    
    @Override
    public void close() throws Exception {
        // 关闭连接的操作
    }
}

Then, when using this custom class, we can directly declare it in the try-with-resources statement:

try (MyConnection connection = new MyConnection()) {
    // 使用connection进行一些操作
} catch (Exception e) {
    e.printStackTrace();
}

in At the end of the try-with-resources statement, Java will automatically call the close method of the MyConnection class to close the connection.

To sum up, try-with-resources is an elegant way to close resources, which can help us release resources more concisely in the code and avoid common resource leak problems. It can not only automatically close some Java built-in resources, but also use custom classes to achieve automatic closing of resources. When writing code, we should actively use try-with-resources statements to improve our code and improve the readability and robustness of the code.

The above is the detailed content of How to gracefully close resources using try-with-resources in Java 7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn