2016-12-20 9 views
1

ソナーがこの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); 
    } 
} 
関連する問題