6. 自动关闭文件
JDK7新增加了一个特性,该特性提供了另一种管理资源的方式,这种方式能自动关闭文件。这个特性有时被称为自动资源管理(Automatic Resource Management, ARM)
。
ARM的主要优点在于 : 当不再需要文件或其他资源时,可以防止无意中忘记释放它们。
基本形式如下 :
try(resource-specification) {
}
但该特性只能针对于实现了AutoCloseable
接口的资源使用带资源的try
语句,所有的流类都实现了这个接口。
package LearnIO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 使用ARM特性
*
* @author cat
* @version 2025/2/27 18:26
* @since JDK17
*/
public class UseRead02 {
public static void main(String[] args) {
// 打开一个文件
try (FileInputStream inputStream = new FileInputStream("D:\\test.txt")) {
int data;
while ((data = inputStream.read()) != -1) {
System.out.print(((char) data));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
输出 :
The will of Kowloon is here.
- try语句中声明的资源被隐式地声明为
final
,这意味着在创建资源变量后不能再将其他资源赋给该变量。