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. 高可用Keepalived+LVS搭建流程

    本流程搭建1个master,1个backup节点的Keepalived,使用lvs轮询2个节点的服务. 一.使用版本 CentOS 7.7 Keepalived 1.3.5 ipvsadm 1.27( ...

  2. arm 添加 samb 文件共享

    编译环境: ubunto 12 arm-linux-gcc 4.3.2 arm linux 4.1.36 开发板 2440 测试上传速度,大文件 github源码 https://github.com ...

  3. Day1T3小w的魔术扑克——图论

    为什么不搞\(T2\)??? 因为我太菜了,那题我是真的搞不出来 题目描述 链接:https://ac.nowcoder.com/acm/contest/1100/C 来源:牛客网 小\(w\)喜欢打 ...

  4. Python进阶学习之面向对象

    目录 面向对象 私有属性 面向对象   python也有面向对象的编程,它与C++中的类有点相似.它也只是运算符重载,继承. class Test: num=0 def __init__(self): ...

  5. (转)windows宿主机,ubuntu虚拟机下的上网设置(有线网络和无线网络)

    转自:http://hi.baidu.com/puppywst/item/d9f73734856e2af32684f4e3 虚拟机下ubuntu共享方式上网: 有线网络 在有线网络的条件下,vmwar ...

  6. Billboard HDU - 2795(树状数组,单点修改,区间查询)

    题目链接:https://vjudge.net/problem/HDU-2795 思路:h = 1e9行不通,因为广告是1*w的,所以n个广告最多只需要 h = n的高度,那么h=2e5就可以接受了. ...

  7. 使用docker构建hadoop集群

    docker的使用越来越普遍了,大家不知道docker的还需要进一步学习一下.这次咱们使用docker去进行hadoop集群的构建. 使用docker构建的好处真的很多,一台电脑上可以学习安装很多想做 ...

  8. C# Bitmap 转 Bytes数组

    首先是Bitmap 转 MemoryStream MemoryStream ms = new MemoryStream(); bitmap.save(ms, ImageFormat.Jpeg); ms ...

  9. ALSA driver---DPCM

    https://www.kernel.org/doc/html/v4.11/sound/soc/dpcm.html Description Dynamic PCM allows an ALSA PCM ...

  10. [UWP]抄抄《CSS 故障艺术》的动画

    1. 前言 什么是故障艺术(Glitch Art 风)?我们熟知的抖音的 LOGO 正是故障艺术其中一种表现形式.它有一种魔幻的感觉,看起来具有闪烁.震动的效果,很吸引人眼球.故障艺术它模拟了画面信号 ...