java中catch的作用_java中try-catch模块中with语句块的作用

以前写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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值