资源释放的两种方式(案例)

167 阅读1分钟
代码繁琐不推荐使用
public static void main(String[] args) {
    InputStream is = null;
    OutputStream op = null;
    try{
       is = new FileInputStream("F:\资料\新建 文本文档.txt");
       op = new FileOutputStream("F:\资料\学习.txt");
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1 ){
            op.write(bytes,0, len);
    }

    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            is.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
        try {
            op.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JDk7的释放资源优化
 try(InputStream is = new FileInputStream("F:\资料\新建 文本文档.txt");
        OutputStream op = new FileOutputStream("F:\资料\学习.txt")
            ){
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1 ){
            op.write(bytes,0, len);
    }
    
    }catch (Exception e){
        e.printStackTrace();
    }
}
JDK9释放资源优化
public static void main(String[] args) throws FileNotFoundException {
    InputStream is = new FileInputStream("F:\资料\新建 文本文档.txt");
    OutputStream op = new FileOutputStream("F:\资料\学习.txt");
    try(is;op){
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1 ){
            op.write(bytes,0, len);
    }

    }catch (Exception e){
        e.printStackTrace();
    }
}