关于Java中的try-with-resources语句

作者:王雀跃 时间:2022-10-21 16:49:54 

介绍

try-with-resources是Java中的环绕语句之一,旨在减轻开发人员释放try块中使用的资源的义务。

它最初在Java 7中引入,背后的全部想法是,开发人员无需担心仅在一个try-catch-finally块中使用的资源的资源管理。这是通过消除对finally块的依赖而实现的。

此外,使用try-with-resources的代码通常更清晰易读,因此使代码更易于管理,尤其是当我们处理许多try块时。

语法

try-with-resources的语法与通常try-catch-finally语法相同。

普通try:

BufferedWriter writer = null;
try {
   writer = new BufferedWriter(new FileWriter(fileName));
   writer.write(str);  // do something with the file we've opened
} catch (IOException e) {
  // handle the exception
} finally {
   try {
       if (writer != null)
           writer.close();
   } catch (IOException e) {
      // handle the exception
   }
}

try-with-resources:

try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){
   writer.write(str); // do something with the file we've opened
}
catch(IOException e){
   // handle the exception
}

Java理解此代码的方式:

try语句之后在括号中打开的资源仅在此处和现在需要。.close()在try块中完成工作后,将立即调用它们的方法。如果在try块中抛出异常,无论如何我会关闭这些资源。

注意

从Java 9开始,没有必要在try-with-resources语句中声明资源。

可以这样做:

BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
try (writer) {
   writer.write(str); // do something with the file we've opened
}
catch(IOException e) {
   // handle the exception
}

来源:https://blog.csdn.net/wangshiqi666/article/details/130431969

标签:Java,try-with-resources,try块
0
投稿

猜你喜欢

  • java 动态增加定时任务示例

    2023-07-29 06:56:00
  • Activiti开发环境的配置

    2021-07-31 21:57:51
  • Java 定时器的多种实现方式

    2021-06-14 03:15:09
  • Android中Textview和图片同行显示(文字超出用省略号,图片自动靠右边)

    2023-02-25 04:52:37
  • Java字符判断的小例子

    2023-08-26 17:29:49
  • Java 抽象类特点总结

    2023-07-28 10:39:46
  • Android远程服务编写和调用教程

    2022-06-14 18:10:45
  • c#制作类似qq安装程序一样的单文件程序安装包

    2021-07-22 17:13:31
  • Android中自定义对话框(Dialog)的实例代码

    2022-01-19 06:10:38
  • java实现在线预览--poi实现word、excel、ppt转html的方法

    2022-09-29 20:29:41
  • Android 7.0调用相机崩溃详解及解决办法

    2023-08-08 21:39:42
  • 详解SpringBoot+Mybatis实现动态数据源切换

    2022-06-04 02:42:02
  • c#使用Unity粒子实现炮塔发射系统

    2023-11-04 19:05:19
  • Spring Boot教程之提高开发效率必备工具lombok

    2021-08-23 11:12:43
  • Android实现圆角Button按钮

    2022-02-04 10:05:45
  • java实现单链表、双向链表

    2023-02-09 03:15:59
  • Android编程开发之NotiFication用法详解

    2023-01-19 22:50:11
  • jdk15的安装与配置全过程记录

    2023-01-06 05:45:10
  • 详解WPF中的隧道路由和冒泡路由事件

    2023-03-01 07:59:49
  • springboot集成fastDfs过程代码实例

    2023-02-21 19:42:20
  • asp之家 软件编程 m.aspxhome.com