Java使用 try-with-resources 实现自动关闭资源的方法

这篇文章主要介绍了Java使用 try-with-resources 实现自动关闭资源的方法,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、 在Java1.7之前,我们需要通过下面这种方法, 在finally中释放资源,这种方法有点繁琐。

 BufferedReader br = null; String str; try { br = new BufferedReader(new FileReader("")); while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }

2、在java1.7之后,可以使用try-with-resources实现自动关闭资源

 try (BufferedReader br = new BufferedReader(new FileReader(""))) { while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }

这样看上去,是不是感觉代码干净了许多,当程序运行完离开try语句块时,( )里的资源就会被自动关闭。

但是try-with-resources还有几个关键点要记住:

①、try()里面的类,必须实现了AutoCloseable接口。
②、在try()代码中声明的资源被隐式声明为fianl。
③、使用分号分隔,可以声明多个资源。

3、自定义类并实现AutoCloseable接口

 class TestAutoClosable implements AutoCloseable { @Override public void close() throws Exception { System.out.println("close"); } public void test() { System.out.println("test"); } }

接下来我们测试下,我们写得自定义类

 try (BufferedReader br = new BufferedReader(new FileReader("E:/test.txt")); TestAutoClosable testAutoClosable = new TestAutoClosable()) { testAutoClosable.test(); } catch (Exception e) { e.printStackTrace(); }

当调用testAutoClosable.test()方法时,下面是控制台打印的:

test
close

可以看到资源被成功关闭。

到此这篇关于Java使用 try-with-resources 实现自动关闭资源的方法的文章就介绍到这了,更多相关java 自动关闭资源内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是Java使用 try-with-resources 实现自动关闭资源的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java