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. [转帖]容器化 TCP Socket 缓存、接收窗口参数

    https://blog.mygraphql.com/zh/notes/low-tec/network/tcp-mem/#rmem_default 最近需要支持一个单 POD 的 TCP 连接数上 1 ...

  2. [转帖]【oracle】oracle查询表存储大小和表空间大小

    目录 查看表分配的物理空间大小 查看表实际存储空间大小 查看每个表空间的大小 查看表空间大小及使用率 查看数据库中数据文件信息 查看临时表空间信息 oracle表大小有两种含义,即表分配的空间大小和实 ...

  3. [转帖]Oracle 性能优化 之 游标及 SQL

    https://www.cnblogs.com/augus007/articles/9273236.html 一.游标 我们要先说一下游标这个概念. 从 Oracle 数据库管理员的角度上说,游标是对 ...

  4. [转帖]Megacli 错误码

    MegaCLI Error Messages 0x00 Command completed successfully 0x01 Invalid command 0x02 DCMD opcode is ...

  5. AI五子棋 C++ 借助图形库raylib和raygui 设计模式思考过程和实现思路总结

    转载请注明 原文链接 :https://www.cnblogs.com/Multya/p/17988499 repo: https://github.com/Satar07/AI_GoBang_Pub ...

  6. 使用css 与 js 两种方式实现导航栏吸顶效果

    场景描述 简单的说一下场景描述:这个页面有三个部分组成的. 顶部的头部信息--导航栏--内容 当页面滚动的时候.导航栏始终是固定在最顶部的. 我们使用的第一种方案就是使用css的粘性定位 positi ...

  7. Element-UI中Drawer抽屉去除标题自带黑色边框

    当点击事件drawer==true时,抽匣回打开 这时抽匣的标题会出现一个难看的蓝色边框,一会就会消失,但是好丑,所以要去掉它 解决方法 /deep/ :focus { outline: 0; } v ...

  8. Golang漏洞管理

    原文在这里 概述 Go帮助开发人员检测.评估和解决可能被攻击者利用的错误或弱点.在幕后,Go团队运行一个管道来整理关于漏洞的报告,这些报告存储在Go漏洞数据库中.各种库和工具可以读取和分析这些报告,以 ...

  9. Windows 核心编程笔记 [1] Windows 错误处理

    [1] Windows 错误处理 1. 关于windows系统函数的返回值错误处理 VOID:这个函数不可能失败 BOOL:如果函数调用失败,返回值为0,即为FALSE,否则为非0值,即为TRUE H ...

  10. C#使用命令行打开diskpart修改盘符

    参考链接: https://www.cnblogs.com/k98091518/p/6019296.html https://learn.microsoft.com/zh-cn/windows-ser ...