标签:写法 ack 完成 语句块 java input tac 特性 final
以前写try-catch时,遇到一些流、连接等对象,必定需要添加finally语句来关闭这些对象。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();
}
}
标签:写法 ack 完成 语句块 java input tac 特性 final
原文地址:http://blog.51cto.com/yuqian2203/2135282