《Effective Java》第9条:try-with-resources优先于try-finally
JAVA with 优先 try Effective resources finally
2023-09-11 14:22:52 时间
220812_《Effective Java》第9条:try-with-resources优先于try-finally
一、问题
Java类库中包含许多需要通过调用close来关闭的资源,例如:InputStream、Output Stream和java.sql.Connection。在编程过程中如果没有关闭会产生性能问题。
二、范例,使用try-finally
使用try-finally来关闭资源,如下所示:
public class FirstLineOfFile_Version1 {
static String firstLineOfFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
}
如果有两个资源,我们会这样来写,但是不推荐这样做。
public class Copy_Version1 {
final static int BUFFER_SIZE = 1024;
static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
}
这样写都能正确关闭资源,但是不推荐这样写,为什么呢?
因为在try块和finally块中都会抛出异常。在这种情况下第二个异常会完全抹除第一个异常。在异常堆栈轨迹中就看不到第一个异常的记录。在现实系统中调试会变得异常复杂。
三、范例,使用try-with-resources
Java 7引入了try-with-resources语句,解决了上述问题。要使用这个构造的资源,就必须实现AutoClosable接口。如果编写了一个类,如果它代表了是必须被关闭的资源,那么这个类也应该实现AutoClosable接口。下面来重写firstLineFoFile以及copy方法:
public class FirstLineOfFile_Version2 {
static String firstLineOfFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
}
如果调用readLine和close方法抛异常,会抛出第一个异常,第二个异常会被禁止。这些禁止的异常不是被抛弃了也会打印在异常堆栈中。
public class Copy_Version2 {
final static int BUFFER_SIZE = 1024;
static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)
) {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
}
}
}
try-with-resources还可以使用catch子句,这样即可以处理异常,又不需要再套用一层代码。
public class FirstLineOfFile_Version3 {
static String firstLineOfFile(String path, String defaultVal) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
return defaultVal;
}
}
}
四、总结
在处理必须关闭的资源时,优先考虑try-with-resources。这样写的代码简洁、清晰,产生的异常也更有参考价值。
相关文章
- [Java基础] java的守护线程与非守护线程
- java -version 问题 : C:ProgramDataOracleJavajavapath;
- JAVA 报错exe4j中this executable was created with an evaluation 怎么办
- Java实现 LeetCode 166 分数到小数
- Java实现 LeetCode 109 有序链表转换二叉搜索树
- java实现第三届蓝桥杯提取子串
- java实现第九届蓝桥杯整理玩具
- Java实现字符串的全排列
- Java实现 蓝桥杯VIP 算法训练 Car的旅行路线
- (Java实现) 洛谷 P1036 选数
- Java 蓝桥杯 算法训练(VIP) 最大体积
- 【JAVA】Java 异常中e的getMessage()和toString()方法的异同
- [Java Spring] Apply default Modelttribute values with @ControllerAdivce
- Java实现大批量数据导入导出(100W以上) -(一)导入
- 转 java实现截图
- java.lang.OutOfMemoryError: Java heap space 解决方法
- [Python] Indexing An Array With Another Array with numpy
- Atitit 搜索蓝牙设备 powershell的实现 java noede.js python 先用脚本语言python nodejs,不好实现。。Java 也不好实现。。 Netcore可以,
- Java 基础知识体系
- java移位运算符实验程序:<<(左移)、>>(带符 号右移)和>>>(无符号右移)
- Java Persistence with Hibernate中文版Hibernate实战第2版勘误
- Java微服务(一)【idea安装2020版本】
- 【java】Java生成微信小程序二维码
- JAVA编程:java环境安装和helloworld
- 【JAVA】【NIO】5、Java NIO Scatter / Gather
- java中接口的定义与实现
- 使用Java操作Elasticsearch(Elasticsearch的java api使用)