网站按天扣费优化推广近一周的新闻大事热点
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);}
}