try-with-resources,优雅的关闭流

介绍

我们都知道,在流使用完之后,都需要进行关闭。以前的写法,都是在try catch finally进行操作,大量的if null判断使代码冗余臃肿。自从jdk1.7之后,有了更优雅的方式:try with resources,大大简化了编码操作。

旧写法

FileOutputStream out = null;
try {
    
    
    out = new FileOutputStream("tmp.txt");
    out.write("123456".getBytes());
    out.flush();
} catch (Exception e) {
    
    
    e.printStackTrace();
} finally {
    
    
    if (null != out) {
    
    
        try {
    
    
            out.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

新写法

  • 要求jdk1.7以上
try(FileOutputStream out = new FileOutputStream("tmp.txt")) {
    
    
    out.write("123456".getBytes());
    out.flush();
} catch (Exception e) {
    
    
    e.printStackTrace();
}
  • 注:使用try with resources的前提条件,需要实现java.lang.AutoCloseable接口。

原理

  • 将上边的代码进行反编译,发现原来是编译器帮我们把代码进行了转换,最终还是在try catch finally进行了流的关闭,但是对于使用者来说这是无感知的。
try {
    
    
    FileOutputStream out = new FileOutputStream("tmp.txt");
    Throwable var2 = null;

    try {
    
    
        out.write("123456".getBytes());
        out.flush();
    } catch (Throwable var12) {
    
    
        var2 = var12;
        throw var12;
    } finally {
    
    
        if (out != null) {
    
    
            if (var2 != null) {
    
    
                try {
    
    
                    out.close();
                } catch (Throwable var11) {
    
    
                    var2.addSuppressed(var11);
                }
            } else {
    
    
                out.close();
            }
        }

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

猜你喜欢

转载自blog.csdn.net/vbhfdghff/article/details/114120378