这篇文章主要介绍了关于Java中的try-with-resources语句,try-with-resources是Java中的环绕语句之一,旨在减轻开发人员释放try块中使用的资源的义务,需要的朋友可以参考下
介绍
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
}
到此这篇关于关于Java中的try-with-resources语句的文章就介绍到这了,更多相关Java try-with-resources语句内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:关于Java中的try-with-resources语句
- Java实现顺序表的操作详解 2023-05-19
- Java中的日期时间处理及格式化处理 2023-04-18
- JSP页面间传值问题实例简析 2023-08-03
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- 深入了解Spring的事务传播机制 2023-06-02
- JSP 制作验证码的实例详解 2023-07-30
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06