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

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

  • 相关阅读:
    Installing Apache Spark on Ubuntu 16.04
    基尼系数(Gini coefficient),洛伦茨系数
    非平衡数据机器学习
    FCM聚类算法介绍
    基于大数据技术的手机用户画像与征信研究
    归一化方法 Normalization Method
    区块链(Blockchain)
    统计抽样
    动态规划 Dynamic Programming
    LTE中的各种ID含义
  • 原文地址:https://www.cnblogs.com/kesuns/p/12712656.html
Copyright © 2011-2022 走看看