Java 7 新的 try-with-resources 语句,自动资源释放
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 接口。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端