`

java 7, try-with-resources

阅读更多

try-with-resources 是jdk 7 开始有的新特性,可以极大的方便写资源创建与释放的程序。常规的资源释放的写法是:

 BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

如果br.close 方法中也可能抛出异常,那么可能还得在finally 中也写try-catch

 

BufferedReader br= new BufferedReader(new FileReader(path));
try {
        return br.readLine();
    } finally {
       try{
           if (br != null) br.close();
            catch(Exception e){
               //do something....
           }
    }

 

有了try-with-resources,可以如下写法,前提是资源实现了java.lang.AutoCloseable接口

 

 try(
   BufferedReader br = new BufferedReader(new FileReader(path))
 ){
        return br.readLine();
} 

如果要创建多个资源,可以直接写几个,而且保证释放的时候会按创建的时候的相反的顺序 来释放。

try(
   Source1 s1=new Source1();
   Source2 s2=new Source2();
 ){
  .....
}

 异常的话,依旧可以catch

try(
   Source1 s1=new Source1();
   Source2 s2=new Source2();
 ){
  //.....
}catch(Exception e){
  //....
} 

 要注意的是,如果是资源使用过程中与close()方法中同时抛出了异常,close()的异常会被“抑制”,为了查询被抑制的异常,调用异常的getSuppressed()方法,注:这也是jdk 7 中加入的特性。

 

try(
   Source1 s1=new Source1();
   Source2 s2=new Source2();
 ){
  //.....
}catch(Exception e){
  //....
  if( e.getSuppressed()!=null){
    //相应的处理
  }
}

 

详细的说明可见官网: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

分享到:
评论

相关推荐

    Java使用 try-with-resources 实现自动关闭资源的方法

    主要介绍了Java使用 try-with-resources 实现自动关闭资源的方法,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

    Java如何优雅地关闭资源try-with-resource及其异常抑制

    主要介绍了Java如何优雅地关闭资源try-with-resource及其异常抑制,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Try-with-resources-Cwiczenie

    Try-with-resources-Cwiczenie

    redis-distribute-lock:Redis分布式锁的try-with-resources实现

    Redis分布式锁的try-with-resources实现 一、简介 在当今这个时代,单体应用(standalone)已经很少了,java提供的synchronized已经不能满足需求,大家自然 而然的想到了分布式锁。谈到分布式锁,比较流行的方法有3...

    Beginning Java 7

    The entire Java language, including Java 7-specific features such as switch on string, try-with-resources, final rethrow, multicatch, and SafeVarargs A huge assortment of Java 7 APIs, beginning with ...

    [第2讲]变量配置.flv

    [第2讲]变量配置flv,[第2讲]变量配置

    java 面试常见问题整理

    如何使用 try-with-resources 代替try-catch-finally? I/O 什么是序列化?什么是反序列化? Java 序列化中如果有些字段不想进行序列化,怎么办? 获取用键盘输入常用的两种方法 Java 中 IO 流分为几种? 既然有了字节...

    3, Java核心技术1 带资源声明的 try 语句

    try-with-resources 语句中的资源只能是实现了java.lang.AutoCloseable接口的类实例,但是 Java SE 7 之後的所有实现了java.io.Closeable的类都实现了java.lang.AutoCloseable接口(该接口是在Java SE 7中才引入的)...

    java7帮助文档

    The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement; see Closing Connections in Processing SQL Statements. RowSet 1.1: The ...

    《Programming in Java Second Edition》高清完整英文PDF版

    To list a few noticeable enhancements, Java 7 includes support for strings in switch statements, try-with-resources statement, improved multi-catch, binary numeric literals, numeric literals with ...

    使用Java API进行tar.gz文件及文件夹压缩解压缩.docx

    解释说明 1.tar文件准确的说是打包文件,将文件打包到一个tar文件中,文件名后缀是.tar 2.Gzip是将文件的存储空间压缩保存,文件名...下文代码中的流操作使用了try-with- resources语法,所以不用写代码手动的close流。

    用java8 Stream流的方式对文本文件逐行处理–.docx

    //try-with-resources语法,不用手动的编码关闭流 try (Stream<String> lines = Files.lines( filePath )) { lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();//只是测试...

    C#编写的windows计算器的实例代码

    介绍了C#编写windows计算器的代码,有需要的朋友可以参考一下

    SQL Server 日期和时间的内部存储过程

    在SQL Server的内部存储中,日期和时间不是以字符串的形式存储的,而是使用整数来存储的。这篇文章主要介绍了SQL Server 日期和时间的内部存储,需要的朋友可以参考下

    使用Java注解处理器实现一个简单的日志记录系统.txt

    process方法用于处理日志文件,它使用了try-with-resources语句来确保资源被正确关闭。在该方法中,创建了一个FileWriter对象用于写入日志文件,并使用PrintWriter对象进行格式化输出。如果在处理过程中发生异常,会...

    Java 9 Revealed: For Early Adoption and Migration

    Java 9 Revealed is for experienced Java programmers looking to make the migration from Java 7 or Java 8 to Java 9.Author Kishori Sharan begins by covering how to develop Java applications using new ...

    积分管理系统java源码-new-and-old:实习过程中的温故知新

    其中对于流的关闭,jdk1.7以上还实现了try-with-resources语句,其原理与上述方法相同。 事务的操作以及数据库锁机制: Spring框架提供了编程式事务管理和声明式事务管理 编程式事务管理: 可以清楚地控制事务的...

    jdk1.7 官方正式版64位下载

    JDK1.7新特性介绍 1. 对Java集合(Collections)的...7. 增加了try-with-resources语句,确保每个资源都在生命周期结束后被关闭 8. 使用泛型增加了类型推断机制 9. 增加了fork/join框架来增强对处理多核并行计算的支持

    The Well Grounded Java MEAP

    The Well-Grounded Java Developer starts with thorough coverage of Java 7 features like try-with-resources and NIO.2. You'll then explore a cross-section of emerging JVM-based languages, including ...

    《剑指offer》Java中的语法糖.pdf

    Java 中的语法糖,真甜 语法糖 泛型 自动拆箱和自动装箱 枚举 内部类 变长参数 增强 for 循环 Switch 支持字符串和枚举 条件编译 断言 try-with-resources 字符串相加 学习语法糖的意义

Global site tag (gtag.js) - Google Analytics