Java – Try with Resources
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的更多相关文章
- Java项目访问resources文件
最近在对接支付宝支付的开发,需要取到支付的RSA公钥和私钥.于是把公钥和私钥加到resources文件夹里.但是不知道怎么读到这两个文件,也就是不知道路径怎么写.于是网上搜索了下如何获取工作路径,Sy ...
- Java工程读取resources中资源文件路径问题
正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径,即相对于当前类的路径.在本地工程和服务器中读取文件的方式有所不同,以下图配置文件为例. 本地读取资 ...
- 普通java工程的resources目录寻址
问题: 普通java工程的src/main/resources目录下的配置文件如何寻址 在src/main/java目录下的代码中如何访问src/main/resources目录下的配置文件? Mav ...
- Java 如何读取resources
Sample in Github 1.一般使用Maven创建Java工程,代码文件在src/main/java文件夹中,资源文件在src/main/resources文件夹中,Java代码为什么可以读 ...
- Java项目读取resources资源文件路径那点事
今天在Java程序中读取resources资源下的文件,由于对Java结构了解不透彻,遇到很多坑.正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径, ...
- java web中resources路径
UserBean.class.getClassLoader().getResource(filePath).getPath() 或者 Thread.currentThread().getContext ...
- [Java] 在 jar 文件中读取 resources 目录下的文件
注意两点: 1. 将资源目录添加到 build path,确保该目录下的文件被拷贝到 jar 文件中. 2. jar 内部的东西,可以当作 stream 来读取,但不应该当作 file 来读取. 例子 ...
- Java获取/resources目录下的资源文件方法
Web项目开发中,经常会有一些静态资源,被放置在resources目录下,随项目打包在一起,代码中要使用的时候,通过文件读取的方式,加载并使用: 今天总结整理了九种方式获取resources目录下文件 ...
- 《Java学习笔记(第8版)》学习指导
<Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...
随机推荐
- redis 出现(error) MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details
如果在ubuntu安装的redis含端口使用,但是某些时候常常出现 (error) MISCONF Redis is configured to save RDB snapshots, but is ...
- python装饰器见解笔记
def zsq(fun): def zsq_n(*args,**kwargs) print('这是装饰器需要运行内容') r = fun(*args,**kwargs) print('在被装饰函数执行 ...
- C++ 别踩白块小游戏练习
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <easyx.h> ...
- C++结构体和类的区别总结及各自优缺点
结构体在栈里.而类在堆里. 结构体为值类型.而类是引用类型 结构体不能被继承,而类可以. 结构体无构造函数 类可以定义虚函数,而结构体不行. 结构在数据参数方面效率更高,简单数组的应用中成本很低.而类 ...
- markdown从入门到放弃word和PDF
Markdown是一个「轻量级」的「标记语言」. 淡定!!!我知道很多"编外人员"看到这句话之后已经没有兴趣再看下去了. 但是请不要关掉这个页面!!! Markdown很简单!!! ...
- beforeEach 之 next
在这里我用通俗点的说法解释上next(),next(false),next('/'),next(error),希望通过这接地气的解释你能掌握这几个知识点.背景:你乘坐汽车从A景区想赶往B景区(模拟路由 ...
- python高阶函数&异常处理
高阶函数 1.什么是高阶函数 在Python中,变量可以指向函数 函数名也是变量 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数. ma ...
- Redis详解(一)
redis简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多 包括string(字符串).list(链表).set(集合).zset(sor ...
- Natas21 Writeup(共用session、session注入)
Natas21: 第一个网页 第二个网页 提示http://natas21.natas.labs.overthewire.org/页面和http://natas21-experimenter.nata ...
- spring官方demo及配置查看
1.http://spring.io/projects/spring-framework 2.https://github.com/spring-projects/spring-mvc-showcas ...