try-with-resource关闭资源流

  •  JDK7之前关闭流资源

    public void oldCopyFile(String orignalUrl,String targetUrl){
        InputStreamReader is = null;
        OutputStreamWriter os = null;

        try {
            is = new InputStreamReader(new FileInputStream(orignalUrl));
            os = new OutputStreamWriter(new FileOutputStream(targetUrl));
            char[] arr = new char[2048];
            while (is.read(arr) != -1){
                os.write(arr);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        //需要在final里面手动关闭各种流,显得非常繁琐
        }finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • JDK7关闭流资源:try-with-resource:不必手动关闭流
   /** 
     * try(
     *   小括号里面声明
     * ){
     *   执行体里面使用资源
     * }
     */

    public void NewCopyFile(String orignalUrl,String targetUrl){

        try (
                InputStreamReader is = new InputStreamReader(new FileInputStream(orignalUrl));
                OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(targetUrl));
        ){
            char[] arr = new char[2048];
            while (is.read(arr) != -1){
                os.write(arr);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • try-with-resource简介
    • Java7引入新特性

    • 优雅的关闭资源

    • 一种Java语法糖:经过反编译之后还是采用jdk7之前的方式关闭流

  • try-with-resource的使用
    • 多资源的自动关闭

    • 需要自动关闭的资源需要实现AutoCloseable接口

    • 避免异常屏蔽(会一层层的将异常抛出来)

  • 资源关闭的特殊情况
    • 资源对象被return的情况下,由调用方关闭

      • 此时在方法内部关闭了资源,调用方拿到的资源不可用

    • ByteArrayInputStream等不需要关闭
    • 使用Socket获取的InputStream和OutputStream对象不需要关闭

      • InputStream和OutputStream对象的关闭会导致Socket关闭

      • 调用Socket的shutdowmInput和shutdownOutput:只会关闭基于Socket的输入流和输出流而不会关闭整个Socket连接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值