Java 7 新的 try-with-resources 语句,自动资源释放

原文地址:https://www.cnblogs.com/my-haohao/p/5627307.html

Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

新的语句支持包括流以及任何可关闭的资源,例如,一般我们会编写如下代码来释放资源:

复制代码
复制代码
    public static void filyCopy(File one,File two){
        FileInputStream fileInput = null;
        FileOutputStream fileOutput = null;
        try {
            fileInput = new FileInputStream(one);
            fileOutput = new FileOutputStream(two);
            byte[] b = new byte[1024];
            int len = 0;
            while((len = fileInput.read(b)) != -1){
                fileOutput.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//释放资源
            try {
                if(fileInput != null){
                    fileInput.close();
                }
                if(fileOutput != null){
                    fileOutput.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }  
复制代码
复制代码

使用 try-with-resources 语句来简化代码如下:

复制代码
复制代码
public static void filyCopy2(File one,File two){
        try (FileInputStream fileInput = new FileInputStream(one);
                FileOutputStream fileOutput = new FileOutputStream(two);){
            byte[] b = new byte[1024];
            int len = 0;
            while((len = fileInput.read(b)) != -1){
                fileOutput.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
复制代码
复制代码

在这个例子中,数据流会在 try 执行完毕后自动被关闭,前提是,这些可关闭的资源必须实现 java.lang.AutoCloseable 接口。

posted @   eyesfree  阅读(323)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示