使用try-with-resources来关闭资源

接触JAVA比较久的朋友都知道,如果要关闭java类库中资源,需要手动调用close方法,比如InputStream,OutputStream,Connection等。自从JDK7开始,java提供了通过try-with-resources语句来实现自动调用close方法(语法糖),这样就可以节省我们手动调用close()方法来关闭资源了。但这里有个前提,就是资源必须实现AutoCloseable接口,好在java中绝大部分常用资源类都实现了这个接口。

现在通过构造AutoCloseable实现类来测试try-with-resources语句。

public class TestClose001 implements AutoCloseable {

    public void run() {
        System.out.println(this.getClass().getName() + "run...");
    }
    @Override
    public void close() throws Exception {
        System.out.println(this.getClass().getName() + " close");
    }
}
public class TestClose002 implements AutoCloseable {

    public void run() {
        System.out.println(this.getClass().getName() + "run...");
    }
    @Override
    public void close() throws Exception {
        System.out.println(this.getClass().getName() + " close");
    }
}

以下是测试类

public class TestCloseMain {

    public static void main(String[] args) throws Exception {
// 这里需要将创建的资源放在try ()括号中声明
try (TestClose001 t001 = new TestClose001(); TestClose002 t002 = new TestClose002();) { t001.run(); t002.run(); } catch (Exception e) { e.printStackTrace(); } } }

执行结果如下:

com.study.effective.createanddestroy.TestClose001run...
com.study.effective.createanddestroy.TestClose002run...
com.study.effective.createanddestroy.TestClose002 close
com.study.effective.createanddestroy.TestClose001 close

通过打印的结果,可以看到后创建的资源会先关闭,这也符合后创建的资源如果依赖先创建的资源,需要优先关闭的原则。所以以后涉及资源调用时,要优先使用try-with-resources语句,而不是try-finally。

posted on 2022-11-20 23:10  阿泰555  阅读(207)  评论(0编辑  收藏  举报

导航