10.2.5 Automatic resource management
10.2.5 自动资源管理
As we have seen earlier, when working with resources, files in particular, it is very important to manage the resources properly within the program. Exceptions can occur at any stage and during the execution of the code, these need to be handled. Using the nested try and finally block does allow us to ensure that all actions related to the file are terminated once the program ends or if an exception occurs. Java does allow some automatic management of resources that implement the AutoCloseable interface, which is defined in the java.lang package. Classes within the Java libraries that deal with file I/O do use this interface. Below is an alternative way of using the try statement, which is termed try with resource.
正如我们之前所看到的,在处理资源,尤其是文件时,在程序中正确管理资源非常重要。异常可能发生在任何阶段,在代码执行期间,需要处理这些异常。使用嵌套的 try 和 finally 块确实可以确保一旦程序结束或发生异常,与文件相关的所有操作都被终止。Java 确实允许对实现 AutoCloseable 接口的资源进行一些自动管理,该接口在 java.lang 包中定义。Java 库中处理文件 I/O 的类确实使用此接口。以下是使用 try 语句的另一种方法,称为 try with resource。
Note the following: 请注意以下事项:
Unlike our last coded example, this code doesn't explicitly call the close() method but the file is still closed and saved.
与我们上一个编码的示例不同,此代码没有显式调用 close() 方法,但文件仍处于关闭状态并保存。Note Line 9 in the code above, how the resources has been associated with the try statement.
请注意上面代码中的第 9 行,资源如何与 try 语句相关联。
This is an alternative way to perform exception handling specific to any resource that could throw an exception.
这是执行特定于可能引发异常的任何资源的异常处理的替代方法。