1、概述
java7引入的try-with-resources特性,允许我们定义在try语句中使用的资源,并在try语句结束的时候自动关闭资源。这些资源必须实现AutoCloseable接口。
2、使用
资源必须在try内部声明并被初始化,如下所示:
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}
3、用try-with-resoruces替换掉try-catch-finally
try-with-resoruces最显而易见的作用就是替换掉传统的try-catch-finally。
对比如下两种不同的例子:
第一个是典型的try-catch-finally,第二个是等价的try-with-resoruces。
Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
4、多个资源的情况下使用try-with-resources
多个资源可以很好的在try-with-resources语句中定义,用分号隔开即可。
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
5 自定义一个AutoCloseable的资源
如果需要一个可以在try-with-resource块中被自动正确关闭的资源,需要定义一个实现了Closeable或AutoCloseable接口的类,并重写close方法。
public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closed MyResource");
}
}
6 资源关闭顺序
最先定义或最先使用的资源最后被关闭;看看下面这个例子:
- 资源1:
public class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
System.out.println("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_First");
}
}
- 资源2:
public class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
System.out.println("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_Second");
}
}
- 代码:
private void orderOfClosingResources() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
af.doSomething();
as.doSomething();
}
}
- 输出:
Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First
7 catch和finally
try-with-resources块也可以有catch和finally。其工作方式和传统的try代码块一样一样的。
8 结论
本文我们讨论了如何使用try-with-resources,并替换try、catch、finally。
自定义实现了AutoCloseable的资源,讨论了资源关闭的顺序。完整的代码见github。
编译:https://www.baeldung.com/java-try-with-resources