[英]Sonar: How to use try-with-resources to close FileOutputStream
Sonar is giving an error that this FileOutputStream
should be closed. 声纳正在给出一个错误,即应关闭此
FileOutputStream
。 I need to modify the following code to use try-with-resources
. 我需要修改以下代码以使用
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);
}
}
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:
而且,当然,你是对的 - 使用try-with-resources解决了这个问题:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.