之前有博客說過IO流關閉工具類,即IOCloseUtil,可即便用了工具類,大多時候,我們關閉流釋放資源的時候,還是要採取try-catch-finally的方式,比如像這種:
public void readTxt() {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("D:\\li\\test.txt");
fileInputStream.read();
} catch (IOException e) {
e.printStackTrace();
} /*finally {
try {
assert fileInputStream != null;
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
finally {
IOCloseUtil.closeAll(fileInputStream);
}
}
public static void main(String[] args) {
new TestAA().readTxt();
}
雖然採用工具類使代碼簡潔了許多,但是JDK1.7以後,我們真沒必要再使用這種方式關閉資源。JDK1.7以後,關閉資源操作便無需層層嵌套在finally中,直接使用try-with-resources即可,這不僅僅讓代碼簡潔不少,而且操作起來相當簡單,如何理解resource?
這個resource可以理解爲實現java.lang.AutoCloseable接口(其中包括實現了java.io.Closeable的所有對象)使用的資源。
public void readTxt() {
try (FileInputStream fileInputStream = new FileInputStream("D:\\li\\test.txt")) {
fileInputStream.read();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TestAA().readTxt();
}
如何判讀資源是否真的被關閉了呢?
public class MyResource implements AutoCloseable {
public void open() {
System.out.println("resource is open!");
}
@Override
public void close() throws Exception {
System.out.println("resource is close!");
}
}
public static void main(String[] args) {
try (MyResource myResource = new MyResource()) {
myResource.open();
} catch (Exception e) {
e.printStackTrace();
}
}
輸出如下:
resource is open!
resource is close!
所以關閉資源採用try-with-resources真的比較方便,至於底層原理,我們可以反編譯class,可以看到JVM還是生成了finally塊。