說說Java7 之 Try with Resources
java7引入Try with Resources文法,允許我們在try塊中聲明并使用資源,確定在使用之後資源被關閉。資源必須實作AuthCloseable接口。
使用Try with Resources
簡單地說,為了自動關閉,資源必須在try塊中聲明并初始化,示例如下:
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}
使用Try with Resources 代替 try–catch-finally
上面方式非常簡潔,是以建議使用Try with Resources 代替傳統的冗長方式:try–catch-finally。
下面通過示例比較兩種方式,首先是采用try–catch-finally,然後采用新的方法,通過Try with Resources實作等價功能:
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();
}
}
然後,使用Try with Resources實作超級簡潔的解決方案:
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
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());
}
}
使用AutoCloseable接口自定義資源
為了建立自定義可被 try-with-resources塊自動處理的資源,則該類需要實作Closeable 或 AutoCloseable 接口,然後重載其close方法:
public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closed MyResource");
}
}
關閉資源順序
最先定義的資源最後被關閉,請看示例:
第一個資源:
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");
}
}
第二個資源:
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
catch 和 finally
使用try-with-resources塊,仍可以有catch 和 finally,它們功能和傳統的try塊一樣。
總結
本文我們讨論了如何使用try-with-resources,通過示例說明如何使用try-with-resources代替try, catch 和 finally。使用AutoCloseable 接口自定義資源以及資源關閉順序。