1.介绍

Java 7中引入的对try-with-resources的支持使我们能够声明将在try块中使用的资源,并确保在执行该块后将关闭资源。

⚠️:声明的资源必须实现AutoCloseable接口。


2.使用try-with-resources

简单地说,要自动关闭,必须在try中声明和初始化资源,如下所示:

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}

3.使用try-with-resources代替try–catch-finally

使用简单明显的try-with-resources代替传统和冗长的try-catch-finally 块。

让我们比较以下代码示例–首先是一个典型的try-catch-finally块,然后是新方法,使用等效的try-with-resources块:

Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}

这是使用try-with-resources的超级简洁解决方案:

try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}

你最钟意那种呢?


4.具有多个资源的try-with-resources

通过用分号分隔多个资源,可以在try-with-resources块中声明多个资源:

try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}

5.自定义实现AutoCloseable接口的资源

要构造一个将由try-with-resources块正确处理的自定义资源,该类应需要实现Closeable或AutoCloseable接口,并覆盖close方法:

public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closed MyResource");
}
}

6.资源关闭顺序

资源首先将会被定义(创建),然后使用,最后被关闭。让我们看一下示例:

资源1:

public class AutoCloseableResourcesFirst implements AutoCloseable {

    public AutoCloseableResourcesFirst() {
System.out.println("Constructor -> AutoCloseableResources_First");
} public void doSomething() {
System.out.println("Something -> AutoCloseableResources_First");
} @Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_First");
}
}

资源2:

public class AutoCloseableResourcesSecond implements AutoCloseable {

    public AutoCloseableResourcesSecond() {
System.out.println("Constructor -> AutoCloseableResources_Second");
} public void doSomething() {
System.out.println("Something -> AutoCloseableResources_Second");
} @Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_Second");
}
}

使用资源:

private void orderOfClosingResources() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { af.doSomething();
as.doSomething();
}
}

输出:

Constructor -> AutoCloseableResources_First

Constructor -> AutoCloseableResources_Second

Something -> AutoCloseableResources_First

Something -> AutoCloseableResources_Second

Closed AutoCloseableResources_Second

Closed AutoCloseableResources_First


7.catch&finally

一个带有资源的try块仍然可以包含catch和finally块,其工作方式与传统try块相同。

8.总结

在本文中,我们讨论了如何使用try-with-resources,如何用try-with-resources替换try,catch和finally,如何使用AutoCloseable构建自定义资源以及了解关闭资源的顺序。


关注笔者公众号,推送各类原创/优质技术文章 ⬇️

Java – Try with Resources的更多相关文章

  1. Java项目访问resources文件

    最近在对接支付宝支付的开发,需要取到支付的RSA公钥和私钥.于是把公钥和私钥加到resources文件夹里.但是不知道怎么读到这两个文件,也就是不知道路径怎么写.于是网上搜索了下如何获取工作路径,Sy ...

  2. Java工程读取resources中资源文件路径问题

    正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径,即相对于当前类的路径.在本地工程和服务器中读取文件的方式有所不同,以下图配置文件为例. 本地读取资 ...

  3. 普通java工程的resources目录寻址

    问题: 普通java工程的src/main/resources目录下的配置文件如何寻址 在src/main/java目录下的代码中如何访问src/main/resources目录下的配置文件? Mav ...

  4. Java 如何读取resources

    Sample in Github 1.一般使用Maven创建Java工程,代码文件在src/main/java文件夹中,资源文件在src/main/resources文件夹中,Java代码为什么可以读 ...

  5. Java项目读取resources资源文件路径那点事

    今天在Java程序中读取resources资源下的文件,由于对Java结构了解不透彻,遇到很多坑.正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径, ...

  6. java web中resources路径

    UserBean.class.getClassLoader().getResource(filePath).getPath() 或者 Thread.currentThread().getContext ...

  7. [Java] 在 jar 文件中读取 resources 目录下的文件

    注意两点: 1. 将资源目录添加到 build path,确保该目录下的文件被拷贝到 jar 文件中. 2. jar 内部的东西,可以当作 stream 来读取,但不应该当作 file 来读取. 例子 ...

  8. Java获取/resources目录下的资源文件方法

    Web项目开发中,经常会有一些静态资源,被放置在resources目录下,随项目打包在一起,代码中要使用的时候,通过文件读取的方式,加载并使用: 今天总结整理了九种方式获取resources目录下文件 ...

  9. 《Java学习笔记(第8版)》学习指导

    <Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...

随机推荐

  1. Javascript中String()和new String()的区别——JS的包装对象

    最近在看Symbol不能使用new操作符,然后类比到Number,String,Boolean,因为它们同属于基本类型,但是有有所差异:Number,String,Boolean是可以使用new操作符 ...

  2. ios background task

    今天要实现一个需求,当用户触摸HOME键,将应用切换到后台时,启动自动备份的任务.这涉及到ios的后台任务处理,本文简单总结一下 首先,ios app有5种状态,分别是:not running, in ...

  3. scrapy 执行同个项目多个爬虫

    一开始我们默认都是只有一个爬虫的,所以执行的代码都是在项目下创建一个py文件 from scrapy import cmdline cmdline.execute('scrapy crawl 爬虫名' ...

  4. java面试题汇总四

    第三部分 Java SE基础 3.1 java多线程 3.1.1 线程的实现方式,怎么启动线程怎么区分线程? 1.线程的实现方式: 有 4 种方式可以用来创建线程: 2.继承 Thread 类   2 ...

  5. Kona JDK 在腾讯大数据领域内的实践与发展

    导语 | 近日,云+社区技术沙龙“腾讯开源技术”圆满落幕.本次沙龙邀请了多位腾讯技术专家,深度揭秘了腾讯开源项目TencentOS tiny.TubeMQ.Kona JDK.TARS以及Medical ...

  6. Linux 文件系统及 ext2 文件系统

      linux 支持的文件系统类型 Ext2:     有点像 UNIX 文件系统.有 blocks,inodes,directories 的概念. Ext3:     Ext2 的加强版,添加了日志 ...

  7. AspNetCore3.1_Secutiry源码解析_1_目录

    文章目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心项目 AspNetCore3.1_ ...

  8. 返回运行方法,可以写在一行 callback&&callback()

    return DiscountMap[discountType] && DiscountMap[discountType](price)

  9. 【Weiss】【第03章】双链表例程

    双链表因为多了个前向指针,需要考虑的特殊因素多了一倍 所以中间插入(这儿没写)和中间删除会比较复杂. 其它倒没什么特别的,代码如下. 测试代码 #include <iostream> #i ...

  10. ML Lecture 0-1: Introduction of Machine Learning

    本博客是针对李宏毅教授在Youtube上上传的课程视频<ML Lecture 0-1: Introduction of Machine Learning>的学习笔记.在Github上也po ...