zoukankan      html  css  js  c++  java
  • try-with-resources语句

    在 JDK 7 之前,各种资源操作需要在finally里面手动关闭

    1 static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
    3     BufferedReader br = new BufferedReader(new FileReader(path));
    4     try {
    5         return br.readLine();
    6     } finally {
    7         if (br != null) br.close();
    8     }
    9 }

    在JDK 7中引入try-with-resources。在引入try-with-resources后,JDK中IO相关操作都可以实现资源自动实现,不需要再finally再手动关闭。

    try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时自动关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

     1 public class Demo {    
     2     public static void main(String[] args) {
     3         try(Resource res = new Resource()) {
     4             res.doSome();
     5         } catch(Exception ex) {
     6             ex.printStackTrace();
     7         }
     8     }
     9 }
    10 
    11 class Resource implements AutoCloseable {
    12     void doSome() {
    13         System.out.println("do something");
    14     }
    15     @Override
    16     public void close() throws Exception {
    17         System.out.println("resource is closed");
    18     }
    19 }

    运行结果为:

    1 do something
    2 resource is closed

    可以看到,资源终止被自动关闭了。

  • 相关阅读:
    Angular 11 中 Schematics 的代码优化
    GoEasy使用阿里云OSS出现的问题
    易班模拟登录-Day1笔记
    类型别名与接口
    TypeScript中的数据类型
    Javascript类型系统
    手写Promise3
    手写Promise2
    手写Promise1
    Promise基础用法2
  • 原文地址:https://www.cnblogs.com/kesuns/p/12712656.html
Copyright © 2011-2022 走看看