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

来源:互联网 发布:售后软件 编辑:程序博客网 时间:2024/06/05 10:18

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

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(){



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

0 0
原创粉丝点击