Java使用 try-with-resources 实现自动关闭资源的方法
作者:C、空白格 时间:2022-01-09 06:54:46
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
可以看到资源被成功关闭。
来源:https://blog.csdn.net/qq_39486119/article/details/106782848
标签:java,try-with-resources,关闭资源
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#实现的json序列化和反序列化代码实例
2022-04-05 22:24:08
Java实现插入公式到PPT的示例代码
2023-11-12 03:04:41
![](https://img.aspxhome.com/file/2023/6/61616_0s.png)
Springboot导出文件,前端下载文件方式
2023-07-21 11:27:05
![](https://img.aspxhome.com/file/2023/4/60774_0s.jpg)
Java中BigDecimal的舍入模式解析(RoundingMode)
2021-10-16 15:28:16
Java中Lombok常用注解分享
2023-06-13 01:32:48
Java的System.getProperty()方法获取大全
2023-11-10 20:12:12
Spring自动装配之方法、构造器位置的自动注入操作
2021-11-30 23:28:40
MyBatis基础支持DataSource实现源码解析
2023-01-16 09:58:07
利用Kotlin + Spring Boot实现后端开发
2022-02-20 05:30:19
![](https://img.aspxhome.com/file/2023/1/69281_0s.jpg)
基于Spring Mvc实现的Excel文件上传下载示例
2022-01-22 02:02:56
Spring Boot 项目发布到 Tomcat 服务器的操作步骤
2023-10-28 09:39:05
java读取文件字符集示例方法
2023-11-09 12:35:39
JavaEE开发之SpringMVC中的自定义消息转换器与文件上传
2023-11-24 19:36:02
![](https://img.aspxhome.com/file/2023/4/59504_0s.jpg)
轻松理解Java面试和开发中的IoC(控制反转)
2023-08-10 03:00:35
![](https://img.aspxhome.com/file/2023/4/58184_0s.jpg)
Java基础之Stream流原理与用法详解
2021-06-07 22:16:05
![](https://img.aspxhome.com/file/2023/5/65195_0s.png)
基于java构造方法Vector查找元素源码分析
2023-11-29 04:33:30
![](https://img.aspxhome.com/file/2023/6/60236_0s.png)
java模拟TCP通信实现客户端上传文件到服务器端
2023-11-26 10:14:49
Spring Boot产生环形注入的解决方案
2023-11-08 20:14:04
Java 超详细图解集合框架的数据结构
2022-04-14 13:09:00
![](https://img.aspxhome.com/file/2023/3/75683_0s.png)
什么是Java自旋锁
2022-09-22 22:10:55
![](https://img.aspxhome.com/file/2023/1/72301_0s.png)