2016-12-20 22 views
1

Sonar提供了一個錯誤,應該關閉這個FileOutputStream。我需要修改以下代碼才能使用try-with-resources。我該怎麼做呢?聲納:如何使用try-with-resources關閉FileOutputStream

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

我重寫了這個問題,說清楚了,我添加了標籤,並改進了標題 – CocoNess

回答

2

當前代碼沒有準備好處理異常 - 您最後會丟失關閉打開的流。當然,你是對的 - 使用試用資源解決了這個問題:

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); 
    } 
}