深入理解 Java 中的 try with resources
warning:
这篇文章距离上次修改已过180天,其中的内容可能已经有所变动。
try-with-resources
是 Java 7 引入的一个新特性,它允许在一个 try
块中声明一种或多种资源,在 try
块结束时自动关闭这些资源。资源是指在程序完成后必须关闭的对象,例如文件、数据库连接等。
使用 try-with-resources
的语法如下:
try (Resource res = createResource()) {
// 使用资源 res
} catch (Exception e) {
// 处理异常
}
其中 Resource
是一个实现了 java.lang.AutoCloseable
接口的资源类,createResource()
是返回资源对象的方法。
以下是一个简单的使用 try-with-resources
的例子:
import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (FileReader fr = new FileReader("example.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个例子中,FileReader
和 BufferedReader
对象都会在 try
块结束后自动关闭,即使发生异常也是如此。这样可以避免在 finally
块中手动关闭资源,从而减少代码量并提高程序的可靠性。
评论已关闭