以前寫try-catch時,遇到一些流、連接等對象,必定需要添加finally語句來關閉這些對象。
今天突然發現try的with模塊可以省略在finally手動關閉的動作,可以通過將這些
對象定義在with模塊中,然後在try語句完成後,自動close對象,前提需要該對象
實現了AutoCloseable或Closeable接口。
然後發現,這個特性其實在java7中就引入了,現在都java9了,才發現。很落伍啊!!!
例如現在的寫法:
try (BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));) {
byte[] buffer = new byte[1024];
int len = -1;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
這樣就夠了,但是以前得多個finally,並且對象定義還得放到try的前面:
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null!=bis){
bis.close();
}
if(null!=bos){
bos.close();
}
}