我曾经写的资源关闭代码,try-catch-finally层层嵌套,finally块里还要再try-catch,简直是一场噩梦。而且一不小心就会忘记关闭,导致资源泄漏。直到我了解了Try-With-Resources语法,世界一下子清净了。
1. 曾经的“噩梦”写法
- 场景: 读取一个文件的内容。
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("path/to/file.txt"));
String line;
while ((line = br.readLine()) != null) {
// 处理每一行
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 必须在这里关闭资源!
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace(); // 关闭资源时也可能出错!
}
}
}代码冗长,容易出错,核心业务逻辑被埋没在异常处理中。
2. 使用Try-With-Resources的“清爽”写法
- 语法: 在
try关键字后的括号里声明和初始化资源。
try (BufferedReader br = new BufferedReader(new FileReader("path/to/file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}看到了吗?finally块消失了! 编译器会自动为我们生成关闭资源的代码,无论是否发生异常,资源都会被正确关闭。
3. 它为什么能工作?
- 前提是,这些资源(如
BufferedReader,FileReader) 都实现了AutoCloseable接口。这个接口只有一个close()方法。 Try-With-Resources语法糖会在编译后帮我们自动调用close()方法。
4. 处理多个资源
- 可以在
try后的括号里用分号分隔多个资源。
try (InputStream is = new FileInputStream("source.zip");
ZipInputStream zis = new ZipInputStream(is);
OutputStream os = new FileOutputStream("output")) {
// 处理压缩文件
} catch (IOException e) {
e.printStackTrace();
}关闭顺序与声明顺序相反(先声明的后关闭)。
总结:
Try-With-Resources是Java 7引入的一个伟大改进,它让代码更简洁、更安全,彻底避免了资源泄漏的风险。只要你使用的类实现了AutoCloseable,就毫不犹豫地用它吧!