try-with-resources

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


传统写法:try-catch-finally

java 复制代码
public static void main(String[] args) {
    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
    try {
        bin = new BufferedInputStream(new FileInputStream(new File("")));
        bout = new BufferedOutputStream(new FileOutputStream(new File("")));
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

JDK 7:try-with-resources

java 复制代码
public static void main(String[] args) {
    try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("")));
         BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("")))) {
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

JDK 9:

try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

java 复制代码
public static void main(String[] args) throws Exception {
    BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("")));
    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("")));
    try (bin;bout) {
        while ((b = bin.read()) != -1) {
            bout.write(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

资源必须实现 AutoClosable 接口,并重写 close 方法

java 复制代码
public class Connection implements AutoCloseable {
	@Override
	public void close(){
	}
}
相关推荐
老毛肚3 分钟前
手写mybatis
java·数据库·mybatis
两点王爷6 分钟前
Java基础面试题——【Java语言特性】
java·开发语言
choke2339 分钟前
[特殊字符] Python 文件与路径操作
java·前端·javascript
choke23314 分钟前
Python 基础语法精讲:数据类型、运算符与输入输出
java·linux·服务器
岁岁种桃花儿26 分钟前
CentOS7 彻底卸载所有JDK/JRE + 重新安装JDK8(实操完整版,解决kafka/jps报错)
java·开发语言·kafka
roman_日积跬步-终至千里1 小时前
【Java并发】Java 线程池实战:警惕使用CompletableFuture.supplyAsync
java·开发语言·网络
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于Springboot的扶贫众筹平台为例,包含答辩的问题和答案
java·spring boot·后端
CodeSheep程序羊1 小时前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
我是咸鱼不闲呀2 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
加油,小猿猿2 小时前
Java开发日志-双数据库事务问题
java·开发语言·数据库