当前位置 博文首页 > FeelTouch:JDK1.7新特性try-with-resources try(){}

    FeelTouch:JDK1.7新特性try-with-resources try(){}

    作者:[db:作者] 时间:2021-07-13 19:12

    基本结构,省区finally:

    try(    ){
    
    }catch(){
    
    }
    写法对比:

    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 资源自动释放特性。

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


    cs