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(){
	}
}
相关推荐
不得了zz7 小时前
04-Spring AI Alibaba ReactAgent 生产级实践:工具调用、结构化输出、HITL 与上下文管理
java·ai编程·springaialibaba
猿究院_夏燊7 小时前
SpringMVC 到底是怎么干活的?
java·网络·职场和发展
鶴哥只手遮天7 小时前
Spring Framework 7.0.9 深度剖析-05-配置元数据解析:XML、注解与 JavaConfig
java·后端·开源
NGINX开源社区7 小时前
与我们交流:NGINX Gateway Fabric 与 NGINX Ingress Controller 社区会议
java·服务器·前端
鶴哥只手遮天7 小时前
Spring Framework 7.0.9 深度剖析-16-异步与调度
java·后端·开源
十年Java程序媛7 小时前
Java 多线程基础与锁机制|进程线程、synchronized、volatile、Lock 面试全梳理
java·spring boot·面试
弈栈录7 小时前
大模型服务抽象:兼容 OpenAI、通义千问与本地模型
java·后端·架构
鶴哥只手遮天8 小时前
Spring Framework 7.0.9 深度剖析-06-Bean 生命周期与依赖注入原理
java·后端·开源
唐钰小宝B8 小时前
深度解读 JDK 8、JDK 11、JDK 17 和 JDK 21 的区别
java·开发语言·windows
golang学习记8 小时前
最新版VS Code开发Spring Boot项目保姆级教程
java·spring boot·vscode·后端