2014-09-03 41 views
1

我正在生成圖像文件的zip文件。但如果找不到圖像,則會生成例如java.util.zip.ZipException: ZIP file must have at least one entry的異常。我正在處理這個異常,但是生成了一個大小爲0的空zip。所以請幫我解決這個問題如何防止製作空的zip文件

try { 
     // create the ZIP file 

     ZipOutputStream out = getOutputStream(subpart, destinationZipPath); 

     /* 
     * ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
     * destinationZipPath)); 
     */ 
     // compress the files 
     LOGGER.error("zip creation is started @" + new Date().toString()); 
     for (String fileNameDB : filesTobeZipped) { 
      // To check duplication of filename in zip creation 
      if (!filesHash.containsKey(fileNameDB)) { 
       filesHash.put(fileNameDB, fileNameDB); 
       File f = new File(sourceFolder + fileNameDB); 
       // to chk file is exists on physical location or not 
       if (f.exists()) { 
        if (fileCount >= batchFileLimit) { 
         out.close(); 
         subpart++; 
         out = getOutputStream(subpart, destinationZipPath); 
         fileCount = 0; 
         // overallSize=0; 
        } 
        FileInputStream in = new FileInputStream(f); 
        // add ZIP entry to output stream 
        out.putNextEntry(new ZipEntry(f.getName())); 
        // transfer bytes from the file to the ZIP file 
        int len; 
        while ((len = in.read(buf)) > 0) { 
         out.write(buf, 0, len); 
        } 
        // complete the entry 
        out.closeEntry(); 
        in.close(); 
        fileCount++; 
       } else { 
       } 
      } 

     } 
     // complete the ZIP file 
     out.close(); // Exception if fileCount=0; 
     return true; 
     // return zipfile; 
    } catch (IOException ex) { 
     return false; 
    } 

回答

2

難道你只是在檢測到第一個存在的文件後創建ZIP流。就像

ZipOutputStream out = null; 

for (String fileNameDB : filesTobeZipped) { 
    if (new File(fileNameDB).exists()) { 
     if (out == null) { 
      out= ZipOutputStream out = getOutputStream(subpart, destinationZipPath); 
     } 

     // do other operations 
    } 
} 
0

你可以這樣來做:

ZipOutputStream out = null; 
try { 
    out = getOutputStream(subpart, destinationZipPath); 
    ... 
    out.close(); // Exception if fileCount=0; 
    return true; 
    // return zipfile; 
} catch (IOException ex) { 
    if (out != null) { 
     out.close(); 
    } 
    destinationZipPath.toFile().delete(); // Or whatever is appropriate. 
    return false; 
} 

也許更好的辦法是有一個try-catch中循環。並檢查文件的數量。

然後你可以使用try-with-resources。