類(lèi)似于InputStream瀑晒、OutputStream 琼梆、Scanner 磨德、PrintWriter等的資源都需要我們調(diào)用close()方法來(lái)手動(dòng)關(guān)閉屯援,一般情況下我們都是通過(guò)try-catch-finally語(yǔ)句:
//讀取文本文件的內(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è)問(wèn)題。
改造上面的代碼:
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寫(xiě)法會(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開(kāi)始,Throwable 類(lèi)新增了 addSuppressed 方法判沟,支持將一個(gè)異常附加到另一個(gè)異常身上耿芹,從而避免異常屏蔽。 - 在try-with-resources后面定義的finally 代碼塊自動(dòng)加到了最外層挪哄。
如果有多個(gè)資源呢吧秕,如何處理?
通過(guò)使用分號(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)置的類(lèi)。你也可以在自己的類(lèi)中實(shí)現(xiàn)java.lang.AutoCloseable接口疗涉,然后在try-with-resources結(jié)構(gòu)里使用這個(gè)類(lèi)拿霉。
AutoClosable 接口僅僅有一個(gè)方法,接口定義如下:
public interface AutoClosable {
public void close() throws Exception;
}
未實(shí)現(xiàn)AutoCloseable接口的類(lèi)無(wú)法使用在try-with-resources結(jié)構(gòu)的try中咱扣,編譯會(huì)報(bào)錯(cuò):
java: 不兼容的類(lèi)型: try-with-resources 不適用于變量類(lèi)型
(java.io.File無(wú)法轉(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語(yǔ)句讓我們更容易編寫(xiě)必須要關(guān)閉的資源的代碼,若采用try-finally則幾乎做不到這點(diǎn)厅克。