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(){
	}
}
相关推荐
jinyishu_7 分钟前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
前端工作日常15 分钟前
我学习到的Java类和对象区别
java·后端
前端工作日常39 分钟前
我学习到的Java类完整结构
java·后端
什巳1 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
宠友信息1 小时前
消息序号如何保证即时通讯源码聊天记录稳定加载
java·spring boot·redis·python·mysql·uni-app
圣光SG1 小时前
Java Web入门基础知识笔记
java·前端·笔记
行思理2 小时前
微信支付“商家转账用户确认模式”,新手教程
java·开发语言·微信
空中湖3 小时前
Spring AI RAG 完整实战:从零搭建企业知识库问答系统
java·人工智能·spring
Ai拆代码的曹操3 小时前
K8s Pod Pending 逐层排查:从 FailedScheduling 到 PVC StorageClass 不存在的实战记录
java·linux·kubernetes
什巳3 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode