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. JMS微服务架构 - 关于事务提交失败,自动重新提交的机制

    用JMS编写的微服务,由调用端决定了各个微服务执行时,是否需要保持事务的一致性. 也就是RemoteClient在调用微服务方法前,先调用BeginTransaction明确后面所调用的微服务需要保持 ...

  2. [转帖]ipv6相关内核参数配置的优化实践

    https://zhuanlan.zhihu.com/p/605217713 调整ARP缓存大小 这个参数通常需要在高负载的访问服务器上增加.比如繁忙的网络(或网关/防火墙 Linux 服务器),再比 ...

  3. [转帖]ls 只显示目录

    https://www.cnblogs.com/lavin/p/5912369.html 只显示目录: ls -d */ 在实际应用中,我们有时需要仅列出目录,下面是 4 种不同的方法. 1. 利用 ...

  4. [转帖]煮饺子与 docker、kubernetes 之间的关系

      前言:云原生的概念最近非常火爆,企业落地云原生的愿望也越发强烈.看过很多关于云原生的文章,要么云山雾罩,要么曲高和寡. 所以笔者就有了写<大话云原生>系列文章的想法,期望用最通俗.简单 ...

  5. [转帖]sendfile“零拷贝”、mmap内存映射、DMA

    https://www.jianshu.com/p/7863667d5fa7 KAFKA推送消息用到了sendfile,落盘技术用到了mmap,DMA贯穿其中. 先说说零拷贝 零拷贝并不是不需要拷贝, ...

  6. [转帖]Linux kernel内存管理之overcommit相关参数

    前言 了解 linux kernel内存管理,首先可以从用户空间的角度来看kernel的内存管理,执行ls /proc/sys/vm的命令,就可以看到vm运行的所有参数,其中就包含了跟overcomm ...

  7. [转帖]如何优雅的使用 Systemd 管理服务

    https://zhuanlan.zhihu.com/p/271071439 背景:我们在构建 Kubernetes 容器化平台时,会在节点上部署各种 agent ,虽然容器化当道的今天很多程序可以直 ...

  8. [知乎]2019-nCov的致死率问题

    https://www.zhihu.com/question/369630554/answer/998649507 知乎 dr.李的文章 跟自己一开始的理解很相似.. 个人也认为死亡率会高于2% 武汉 ...

  9. Mysql数据库查看Database的大小的方法

    最简单的方法为: select concat(round(sum(data_length/1024/1024),2),'MB') as data from INFORMATION_SCHEMA.tab ...

  10. systemctl 关闭图形界面的办法

    开机以命令模式启动,执行: systemctl set-default multi-user.target   开机以图形界面启动,执行: systemctl set-default graphica ...