使用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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!