Java - Try with Resources

Try with Resources

翻译来源: Eugen Paraschiv 的 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

先声明的先构造,方法顺序为调用顺序,close为后声明的先关闭!!

7.catch 和 finally

try-with-resources块仍然可以拥有catch和finally块 - 这将与传统的try块一样工作。

8.总结

在本文中,我们讨论了如何使用try-with-resources,如何替换try,catch,最后使用try-with-resources,使用AutoCloseable构建自定义资源以及关闭资源的顺序。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值