首页 > 编程语言 > 详细

JAVA中的 try( ){ } ==== 》 try-with-resources 资源自动释放

时间:2015-02-26 01:23:17      阅读:311      评论:0      收藏:0      [点我收藏+]

前一阵子看到一个异常处理的结构,但是一直忘了发博客学习,今天看书又看到了这个异常处理、

try(    ){



}catch(){


}


类似于这个结构。

这种结构叫做try-with-resources.自动资源释放。

这种特性从JDK1.7开始存在的。


例如下列代码:

private static void customBufferStreamCopy(File source, File target) {
    InputStream fis = null;
    OutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
  
        byte[] buf = new byte[8192];
  
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
    }
}
  
private static void close(Closeable closable) {
    if (closable != null) {
        try {
            closable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





上述代码对于异常处理十分复杂,

对于资源的关闭也很麻烦,那么可以和下面的进行对比:


private static void customBufferStreamCopy(File source, File target) {
    try (InputStream fis = new FileInputStream(source);
        OutputStream fos = new FileOutputStream(target)){
  
        byte[] buf = new byte[8192];
  
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}



这段代码就用到了这种 try-with-resources 资源自动释放特性。


在try(    ) {   

 

}catch(){



}结束后资源也自动的关闭,释放掉了。就没有必要写出手动的关闭。


JAVA中的 try( ){ } ==== 》 try-with-resources 资源自动释放

原文:http://blog.csdn.net/u012965373/article/details/43944663

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!