问题
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);
}
}
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/41248572/sonar-how-to-use-try-with-resources-to-close-fileoutputstream