Sonar: How to use try-with-resources to close FileOutputStream(声纳:如何使用 try-with-resources 关闭 FileOutputStream)
问题描述
Sonar 给出了一个错误,提示该 FileOutputStream
应该被关闭.我需要修改以下代码以使用 try-with-resources
.我该怎么做?
Sonar is giving an error that this FileOutputStream
should be closed. I need to modify the following code to use try-with-resources
. How do I do this?
public void archivingTheFile(String zipFile){
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String file : this.fileList){
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
}catch(IOException ex){
LOGGER.error("Exception occurred while zipping file",ex);
}
}
推荐答案
当前代码还没有准备好处理异常 - 你缺少 finally 块来关闭打开的流.而且,当然,你是对的 - 使用 try-with-resources 解决了这个问题:
Currently code is not ready to handle exceptions - you're missing finally block to close open streams. And, sure, you're right - using try-with-resources solves this problem:
public void archivingTheFile(String zipFile) {
byte[] buffer = new byte[1024];
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
for(String file : this.fileList) {
try (FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file)) {
ZipEntry ze = new ZipEntry(file);
zos.putNextEntry(ze);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
}
} catch(IOException ex) {
LOGGER.error("Exception occurred while zipping file",ex);
}
}
这篇关于声纳:如何使用 try-with-resources 关闭 FileOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声纳:如何使用 try-with-resources 关闭 FileOutputStream
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01