使用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   阿泰555  阅读(223)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示