類似于InputStream、OutputStream 、Scanner 、PrintWriter等的資源都需要我們調(diào)用close()方法來手動(dòng)關(guān)閉,一般情況下我們都是通過try-catch-finally語句:
//讀取文本文件的內(nèi)容
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();
}
}
這樣做是不是很麻煩?既要進(jìn)行資源非空判斷還要對(duì)close進(jìn)行捕獲異常,弄不好就可能有資源忘了關(guān)閉。
在 JDK 1.7 之后的 try-with-resources 可以完美解決這個(gè)問題。
改造上面的代碼:
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("執(zhí)行finally");
}
}
其實(shí)try-with-resources寫法會(huì)自動(dòng)加上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("執(zhí)行finally");
}
}
- 自動(dòng)生成了關(guān)閉資源的finally 代碼塊;
- 而且將scanner.close()拋出的異常和new Scanner()拋出異常,addSuppressed合并到了一起。解決了
異常屏蔽
;從JDK 1.7開始,Throwable 類新增了 addSuppressed 方法,支持將一個(gè)異常附加到另一個(gè)異常身上,從而避免異常屏蔽。 - 在try-with-resources后面定義的finally 代碼塊自動(dòng)加到了最外層。
如果有多個(gè)資源呢,如何處理?
通過使用分號(hào)分隔,可以在try-with-resources塊中聲明多個(gè)資源。
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 實(shí)現(xiàn)
這個(gè)try-with-resources結(jié)構(gòu)里不僅能夠操作java內(nèi)置的類。你也可以在自己的類中實(shí)現(xiàn)java.lang.AutoCloseable接口,然后在try-with-resources結(jié)構(gòu)里使用這個(gè)類。
AutoClosable 接口僅僅有一個(gè)方法,接口定義如下:
public interface AutoClosable {
public void close() throws Exception;
}
未實(shí)現(xiàn)AutoCloseable接口的類無法使用在try-with-resources結(jié)構(gòu)的try中,編譯會(huì)報(bào)錯(cuò):
java: 不兼容的類型: try-with-resources 不適用于變量類型
(java.io.File無法轉(zhuǎn)換為java.lang.AutoCloseable)
任何實(shí)現(xiàn)了這個(gè)接口的方法都可以在try-with-resources結(jié)構(gòu)中使用。
下面是一個(gè)簡(jiǎn)單的例子:
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執(zhí)行");
}
}
doSome
closed
finally執(zhí)行
使用try-with-resources以后就不要擔(dān)心使用資源不關(guān)閉了。
面對(duì)必須要關(guān)閉的資源,我們總是應(yīng)該優(yōu)先使用 try-with-resources 而不是try-finally。隨之產(chǎn)生的代碼更簡(jiǎn)短,更清晰,產(chǎn)生的異常對(duì)我們也更有用。try-with-resources語句讓我們更容易編寫必須要關(guān)閉的資源的代碼,若采用try-finally則幾乎做不到這點(diǎn)。