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

以前写try-catch时,遇到一些流、连接等对象,必定需要添加finally语句来关闭这些对象。
今天突然发现try的with模块可以省略在finally手动关闭的动作,可以通过将这些
对象定义在with模块中,然后在try语句完成后,自动close对象,前提需要该对象
实现了AutoCloseableCloseable接口。
然后发现,这个特性其实在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();
        }
}

猜你喜欢

转载自blog.51cto.com/yuqian2203/2135282
今日推荐