当前位置: 首页 > news >正文

Java try-with-resources 显性 与 隐性 关闭 资源

try-with-resources 是 Java 7 引入的一个语言特性,用于简化资源管理的代码,特别是在处理需要关闭的资源(如文件、网络连接、数据库连接等)时。try-with-resources 允许您在 try 语句中声明需要关闭的资源,这些资源会在 try 块执行完毕后自动关闭,无需显式调用关闭方法或者使用 finally 块。

Uijt!jt!uif!ebub!up!cf!fodszqufe/

package net.Java;import java.io.*;public class EncryptionFilterOutputStreamExample {public static void main(String[] args) {String data = "This is the data to be encrypted.";byte[] bytes = data.getBytes();//以下内容隐性关闭输出流,即没有 finally下使用close;try (FileOutputStream fileOutputStream = new FileOutputStream("encrypted_data.txt");FilterOutputStream filterOutputStream = new EncryptionFilterOutputStream(fileOutputStream)) {filterOutputStream.write(bytes);} catch (IOException e) {e.printStackTrace();}//以下内容显性关闭输出流,即 finally下使用close;OutputStream out = System.out;FilterOutputStream filterOutputStream = new EncryptionFilterOutputStream(out);try {filterOutputStream.write(bytes);} catch (IOException e) {e.printStackTrace();}finally {try {filterOutputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}class EncryptionFilterOutputStream extends FilterOutputStream {public EncryptionFilterOutputStream(OutputStream out) {super(out);}@Overridepublic void write(int b) throws IOException {// Simple encryption: Add 1 to the byte value before writingout.write(b + 1);}
}

http://www.lryc.cn/news/119947.html

相关文章:

  • Vue在页面输出JSON对象,测试接口可复制使用
  • 【STM32】FreeRTOS开启后,不再进入主函数的while(1)
  • Python+Selenium+Unittest 之selenium11--WebDriver操作方法1-常用操作
  • 气液固三相线识别—Langmuir部分复现
  • Redis——常见数据结构与单线程模型
  • 大数据-玩转数据-Flink-Transform
  • Java泛型集合简明教程
  • Prometheus-RabbitMQ Exporter
  • flink读取kafka数据存储iceberg
  • 文章二:分支管理策略 - 分支玩转:Git分支管理实战
  • JS dom元素和鼠标位置之间的一系列属性快速参考
  • 【剑指 Offer 39】数组中超过一半的数字
  • list.stream.filter,List<List>转换为List
  • 手机里视频太大怎么压缩?压缩教程分享
  • Spring-Cloud-Loadblancer详细分析_3
  • 使用 VScode 开发 ROS 的Python程序(简例)
  • 2022年03月 C/C++(一级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • HarmonyOS/OpenHarmony应用开发-ArkTSAPI系统能力SystemCapability列表
  • 【01】基础知识:typescript安装及使用,开发工具vscode配置
  • 用C++实现的RTS游戏的路径查找算法(A*、JPS、Wall-tracing)
  • helm 制作应用的离线安装包
  • RN实现混合式开发-内嵌html
  • 2000-2022年全国各地级市绿色金融指数数据
  • MachineLearningWu_13/P60-P64_Tensorflow
  • centos7实现负载均衡
  • Django笔记之数据库函数之日期函数
  • 系统架构师---开发方法---敏捷开发
  • 数据中心液冷技术:规模扩张的新里程碑
  • 页面静态化(模板引擎Freemarker)
  • 详细记录Pycharm配置已安装好的Conda虚拟环境