Java 资源的释放方法

close()放在finally块中


PrintWriter out = null;
try {
    out = new PrintWriter(
        new BufferedWriter(
        new FileWriter("out.txt", true)));
    out.println("the text");
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (out != null) {
        out.close();
    }

这种方式在JDK1.7之前,推荐使用这种方式,但是,这种方式还是有问题,因为,在try块和finally块中可能都会发生Exception。

使用try-with-resource语句


try (PrintWriter out2 = new PrintWriter(
            new BufferedWriter(
            new FileWriter("out.txt", true)))) {
    out2.println("the text");
} catch (IOException e) {
    e.printStackTrace();
}

推荐jdk版本在1.7以上。

关于 try-with-resource 的解释一个很好的文章:https://www.cnblogs.com/itZhy/p/7636615.html

猜你喜欢

转载自blog.51cto.com/82711020/2148087