類似于InputStream、OutputStream 、Scanner 、PrintWriter等的資源都需要我們調用close()方法來手動關閉,一般情況下我們都是通過try-catch-finally語句:
//讀取文本文件的內容
Scanner scanner = null;
try {
scanner = new Scanner(new File("D://read.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
這樣做是不是很麻煩?既要進行資源非空判斷還要對close進行捕獲異常,弄不好就可能有資源忘了關閉。
在 JDK 1.7 之后的 try-with-resources 可以完美解決這個問題。
改造上面的代碼:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}finally {
System.out.println("執行finally");
}
}
其實try-with-resources寫法會自動加上close的代碼,反編譯一下:
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("test.txt"));
Throwable var2 = null;
try {
while(scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (Throwable var20) {
var2 = var20;
throw var20;
} finally {
if (scanner != null) {
if (var2 != null) {
try {
scanner.close();
} catch (Throwable var19) {
var2.addSuppressed(var19);
}
} else {
scanner.close();
}
}
}
} catch (FileNotFoundException var22) {
var22.printStackTrace();
} finally {
System.out.println("執行finally");
}
}
- 自動生成了關閉資源的finally 代碼塊;
- 而且將scanner.close()拋出的異常和new Scanner()拋出異常,addSuppressed合并到了一起。解決了
異常屏蔽
;從JDK 1.7開始,Throwable 類新增了 addSuppressed 方法,支持將一個異常附加到另一個異常身上,從而避免異常屏蔽。 - 在try-with-resources后面定義的finally 代碼塊自動加到了最外層。
如果有多個資源呢,如何處理?
通過使用分號分隔,可以在try-with-resources塊中聲明多個資源。
try (BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(
new FileOutputStream(new File("out.txt")))) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
} catch (IOException e) {
e.printStackTrace();
}
自定義AutoClosable 實現
這個try-with-resources結構里不僅能夠操作java內置的類。你也可以在自己的類中實現java.lang.AutoCloseable接口,然后在try-with-resources結構里使用這個類。
AutoClosable 接口僅僅有一個方法,接口定義如下:
public interface AutoClosable {
public void close() throws Exception;
}
未實現AutoCloseable接口的類無法使用在try-with-resources結構的try中,編譯會報錯:
java: 不兼容的類型: try-with-resources 不適用于變量類型
(java.io.File無法轉換為java.lang.AutoCloseable)
任何實現了這個接口的方法都可以在try-with-resources結構中使用。
下面是一個簡單的例子:
public class MyAutoClosable implements AutoCloseable {
public void doSome() {
System.out.println("doSome");
}
@Override
public void close() throws Exception {
System.out.println("closed");
}
}
public static void main(String[] args) {
try (MyAutoClosable myAutoClosable = new MyAutoClosable()) {
myAutoClosable.doSome();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally執行");
}
}
doSome
closed
finally執行
使用try-with-resources以后就不要擔心使用資源不關閉了。
面對必須要關閉的資源,我們總是應該優先使用 try-with-resources 而不是try-finally。隨之產生的代碼更簡短,更清晰,產生的異常對我們也更有用。try-with-resources語句讓我們更容易編寫必須要關閉的資源的代碼,若采用try-finally則幾乎做不到這點。