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(){
	}
}
相关推荐
黎雁·泠崖18 分钟前
Java 包装类:基本类型与引用类型的桥梁详解
java·开发语言
盖头盖1 小时前
【Java反序列化基础】
java
极客先躯2 小时前
高级java每日一道面试题-2025年7月15日-基础篇[LangChain4j]-如何集成国产大模型(如通义千问、文心一言、智谱 AI)?
java·人工智能·langchain·文心一言·异常处理·密钥管理·参数调优
追随者永远是胜利者2 小时前
(LeetCode-Hot100)226. 翻转二叉树
java·算法·leetcode·职场和发展·go
芒克芒克2 小时前
深入浅出Java线程池(一)
java·开发语言
wuqingshun3141592 小时前
红黑树有哪些特征
java·开发语言·jvm
fchampion3 小时前
最终一致性
java·spring·rabbitmq·github·mvc
wuqingshun3141593 小时前
说一下什么是fail-fast
java·开发语言·jvm
wuqingshun3141593 小时前
知道java NIO吗?和java IO有什么区别?
java·开发语言·jvm
AC赳赳老秦3 小时前
2026多模态技术趋势预测:DeepSeek处理图文音视频多格式数据实战指南
java·人工智能·python·安全·架构·prometheus·deepseek