1.介绍

从Java7诞生了try-with-resources,这家伙可以在资源使用完后实现自动关闭回收。想想我们之前打开一个文件或流对象用完咋整的,是不是finally语句块中手动close的。

当然这类可自动关闭的资源前提是必须实现了AutoCloseable接口。

2.如何使用?

拿PrintWriter对象举例,资源必须在try结构中声明和初始化:

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

看下JDK1.8中PrintWriter的定义:

All Implemented Interfaces:

Closeable, Flushable, Appendable, AutoCloseable

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

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-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 (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接口的资源

前提是要实现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.Java9中的改进

来到java9我们可以在try-with-resources块中使用final或effectively final变量:

final Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
try (scanner;writer) {
// omitted
}

如上,scanner变量声明为final,而writer变量没有显式声明final,但是很明显它在第一次赋值后并没有做其它改变,java8开始自动认为其为final变量。这一特性也就是effectively final。

Java中的Try with Resources语句介绍的更多相关文章

  1. 转载:Java中的字符串常量池详细介绍

    引用自:http://blog.csdn.net/langhong8/article/details/50938041 这篇文章主要介绍了Java中的字符串常量池详细介绍,JVM为了减少字符串对象的重 ...

  2. java中的compareto方法的详细介绍

    java中的compareto方法的详细介绍 Java Comparator接口实例讲解(抽象方法.常用静态/默认方法) 一.java中的compareto方法 1.返回参与比较的前后两个字符串的as ...

  3. Java中Synchronized的用法(简单介绍)

    简单介绍 synchronized是Java中的关键字,是一种同步锁.它修饰的对象有以下几种: 1. 修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用的对象是调 ...

  4. java中的包以及内部类的介绍

    1:形式参数和返回值的问题(理解)    (1)形式参数:        类名:需要该类的对象        抽象类名:需要该类的子类对象        接口名:需要该接口的实现类对象    (2)返 ...

  5. 原来java中也有类似goto语句的标签啊--java label标签

    http://blog.sina.com.cn/s/blog_6d5354cd0100xjg7.html ——————————————————————————————————————————————— ...

  6. java中equals以及==的用法(简单介绍)

    简单介绍 equals方法是java.lang.Object类的方法 有两种用法说明: 一.对于字符串变量来说,使用“==”和“equals()”方法比较字符串时,其比较方法不同. 1.“==”比较两 ...

  7. java中Executor、ExecutorService、ThreadPoolExecutor介绍(转)

    1.Excutor 源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /**     * Executes th ...

  8. java中Executor、ExecutorService、ThreadPoolExecutor介绍

    源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /**      * Executes the given c ...

  9. java中异常处理finally和return语句的执行顺序

    finally代码块的语句在return之前一定会得到执行 如果try块中有return语句,finally代码块没有return语句,那么try块中的return语句在返回之前会先将要返回的值保存, ...

  10. Java中if else条件判断语句的执行顺序

    学习目标: 掌握 if else 条件判断的使用 学习内容: 1.if语法 if(boolean表达式) { 语句体; } if后面的{}表示一个整体-代码块,称之为语句体,当boolean表达式为t ...

随机推荐

  1. [转帖]mysql 里 CST 时区的坑

    mysql 里 CST 时区的坑 一.问题简述 mysql 里 CST 时区是个非常坑的概念,因为在 mysql 里CST既表示中国也表示美国的时区.但是在Jdk代码里,CST 这个字符串被理解为Ce ...

  2. [转帖]配置ftp连接对象存储bucket子目录的方法

    https://developer.jdcloud.com/article/1838 配置ftp连接对象存储bucket子目录的方法  京东云技术交付部  2021-01-27 IP归属:未知 441 ...

  3. [1036]Linux启动时间分析

    简述 今天有同事咨询:项目上有台服务器操作系统启动时间较长,如何分析? 果然,好问题都来自实践. 经过查找,对于所有基于systemd的系统,可以使用systemd-analyze来分析系统启动时间. ...

  4. CentOS8 安装Oracle19c RPM的办法

    1. 下载相应的rpm包 我这边使用的主要有: -rw-r--r-- 1 root root 19112 Apr 5 15:13 compat-libcap1-1.10-7.el7.x86_64.rp ...

  5. Linux 排除某些目录下 重复jar包的方法

    Linux 排除某些目录下 取重复jar包的方法 find . -path ./runtime/java -prune -o -name '*.jar' -exec basename {} \;| s ...

  6. echasrts定义折线图legend的样式-优化

    option = { title: { text: '折线图堆叠' }, tooltip: { trigger: 'axis' }, //定义折线图legend的形状哈 legend: { itemW ...

  7. 你知道css3渐变吗线性渐变和径向渐变

    线性渐变 #app { width: 200px; height: 200px; background: linear-gradient(to bottom, red, green); /*从顶部到底 ...

  8. c#通过表达式树优雅的实现分组取TopN笔记

    需要引入nuget包来实现ef.functions调用row_number Thinktecture.EntityFrameworkCore.SqlServer 调用方式: //顺排 context. ...

  9. Harbor系统文章01---Linux安装Harbor

    1.切换到指定目录下载harbor安装包 wget https://ghproxy.com/https://github.com/goharbor/harbor/releases/download/v ...

  10. MongoDB 选型介绍

    什么是 MongoDB 前言 MongoDB 的主要特性 MongoDB 对比关系型数据库 MySQL 什么时候考虑 MongoDB 参考 什么是 MongoDB 前言 MongoDB 是一个开源.高 ...