java1.7特性,叫做try-with-resource,实现了AutoCloseable接口的实例可以放在try(...)中
在离开try块时将自动调用close()方法。该方法调用可以看做在finally块中,所以资源的释放一定会执行,不过能不能成功释放还是得看close方法是否正常返回。
在离开try块时将自动调用close()方法。该方法调用可以看做在finally块中,所以资源的释放一定会执行,不过能不能成功释放还是得看close方法是否正常返回。
原来:
InputStream is = null;
OutputStream os = null;
try {
//...
} catch (IOException e) {
//...
}finally{
try {
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
} catch (IOException e2) {
//...
}
}
现在可以写成:
try(
InputStream is = new FileInputStream("...");
OutputStream os = new FileOutputStream("...");
){
//...
}catch (IOException e) {
//...
}