黑客日教程-Java带资源的try语句(try-with-resources)

1、概述

java7引入的try-with-resources特性,允许我们定义在try语句中使用的资源,并在try语句结束的时候自动关闭资源。这些资源必须实现AutoCloseable接口。

2、使用

资源必须在try内部声明并被初始化,如下所示:

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

3、用try-with-resoruces替换掉try-catch-finally

try-with-resoruces最显而易见的作用就是替换掉传统的try-catch-finally。
对比如下两种不同的例子:
第一个是典型的try-catch-finally,第二个是等价的try-with-resoruces。

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();
    }
}

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-resource块中被自动正确关闭的资源,需要定义一个实现了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-with-resources块也可以有catch和finally。其工作方式和传统的try代码块一样一样的。

8 结论

本文我们讨论了如何使用try-with-resources,并替换try、catch、finally。
自定义实现了AutoCloseable的资源,讨论了资源关闭的顺序。完整的代码见github

编译:https://www.baeldung.com/java-try-with-resources

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值