美文网首页
commons.io-2.6 closeQuietly()已过时

commons.io-2.6 closeQuietly()已过时

作者: 湖与月 | 来源:发表于2018-12-31 15:20 被阅读0次

    closeQuietly()的使用

    我想用过IOUtils.closeQuietly(out)的人都会对它爱不释手,因为它大大简化了流的关闭操作。
    使用前:

     finally {
           if (in != null) {
              try {
                  in.close();
              } catch (IOException e) {
                  xxxxxx
              }
           }
           if (out != null) {
              try {
                  out.close();
              } catch (IOException e) {
                 xxxxxx
              }
           }
     } 
    

    使用后:

    finally {
           IOUtils.closeQuietly(out);
     }
    

    这真的让人看着舒服了很多。
    但是在2.6版本的时候,它过时了……

    过时原因的个人见解

    我发现在2.5版本及其使用Java6时还是有效的,而在2.6时,它才发生了改变,这时它已经用起了Java7。后来我也在StackOverflow上找到了原因:

    出错时,忽略异常

    public static void closeQuietly(Closeable closeable) {
            try {
                if (closeable != null) {
                    closeable.close();
                }
            } catch (IOException var2) {
                ;
            }
    
        }
    

    其实它也不是不安全,毕竟处理流的过程中出错了话,已经有其他try catch包围了,closeQuietly()只是确保流会被关闭,无论流是否正常结束。

    try-with-resource的出现

    那么为什么会在2.6的时候将它标记为过时呢?因为Java7里的“try-with-resource”语法的出现。
    使用方式:

    try (
           ByteArrayOutputStream out = new ByteArrayOutputStream();
       ) {
           // Do something
       } finally {
            
       }
    

    之前定义在try catch外部的流移到了try后边的括号里,然后finally里就不再需要手动关闭了,它会自行处理。
    怎么处理呢?看它编译后的模样:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Throwable var10 = null;
    
    byte[] resultDatas;
    try {
        // Do something
    } catch (Throwable var20) {
        var10 = var20;
        throw var20;
    } finally {
        if (out != null) {
            if (var10 != null) {
                try {
                    out.close();
                } catch (Throwable var19) {
                    var10.addSuppressed(var19);
                }
            } else {
                out.close();
            }
        }
    
    }
    

    所以“try-with-resource”就是所谓的语法糖,帮我们省事了而已。

    结论:用try-with-resource代替IOUtils.closeQuietly(out)

    所以官方还是建议大家多使用“try-with-resource”,不过在这里给大家避个坑

    使用“try-with-resource”后,无法再进行赋值操作

    image.png

    可知,在try()内定义的流相当于加了final标记,你无法再改变其内存引用地址。

    相关文章

      网友评论

          本文标题:commons.io-2.6 closeQuietly()已过时

          本文链接:https://www.haomeiwen.com/subject/dznilqtx.html