try-with-resources 是 Java 7 引入的语法糖,用于 自动 管理资源(如文件流、数据库连接等),确保资源在使用后被正确关闭,避免资源泄漏。
语法糖 是什么?语法糖 (Syntactic Sugar)是计算机语言中对语法进行的一些改动,使得代码更易于人类阅读和编写,但并不改变语言的功能或表达能力。本质上,编译器 / 解释器会在背后把这些 "甜语法" 转换成语言原本的基础语法来执行。
回到我们的 try-with-resources。
基本语法:- try (ResourceType resource = new ResourceType()) {
- // 使用资源的代码
- } catch (Exception e) {
- // 异常处理
- }
复制代码 资源类 必须实现 AutoCloseable 或 Closeable 接口:- public interface AutoCloseable {
- void close() throws Exception;
- }
- public interface Closeable extends AutoCloseable {
- void close() throws IOException;
- }
复制代码 传统 finally 方式(繁琐易出错):- BufferedReader br = null;
- try {
- br = new BufferedReader(new FileReader("test.txt"));
- // 业务代码
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 必须判空 + 嵌套try-catch(close()也会抛异常)
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码 try-with-resources 方式(简洁健壮):- try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
- // 业务代码
- } catch (Exception e) {
- e.printStackTrace();
- }
复制代码 单个资源:- try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
- String line;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
复制代码 多个资源(支持在括号内声明多个资源,用;分隔):- try (InputStream in = new FileInputStream("input.txt");
- OutputStream out = new FileOutputStream("output.txt")) {
-
- byte[] buffer = new byte[1024];
- int bytesRead;
- while ((bytesRead = in.read(buffer)) != -1) {
- out.write(buffer, 0, bytesRead);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
复制代码 资源顺序(多个资源按声明顺序关闭 - 后声明的先关闭):- // 声明顺序:Connection → PreparedStatement → ResultSet
- try (Connection conn = DriverManager.getConnection(url, user, pwd);
- PreparedStatement ps = conn.prepareStatement("SELECT * FROM user");
- ResultSet rs = ps.executeQuery()) {
- // 业务逻辑
- }
- // 关闭顺序:ResultSet → PreparedStatement → Connection
复制代码 try-with-resources 是 Java 开发中资源管理的首选方式,大大减少了资源泄漏的风险,提高了代码的可读性和可维护性。
痛苦本身也是生活。-- 烟沙九洲
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |