2013-10-03 108 views
1

我正在研究一種方法,該方法將採用壓縮文件,將其解壓縮,並返回包含所有解壓縮文件的新文件/目錄。我們的目標是接下來的目錄並從中提取一個excel文檔,然後將其轉換爲我構建的Workbook類(它完全通過單元測試並且工作正常)。問題是,我得到以下異常:ZipException:在打開zip文件時出錯

java.util.zip.ZipException: error in opening zip file 
at java.util.zip.ZipFile.open(Native Method) 
at java.util.zip.ZipFile.<init>(ZipFile.java:215) 
at java.util.zip.ZipFile.<init>(ZipFile.java:145) 
at java.util.zip.ZipFile.<init>(ZipFile.java:159) 
at com.atd.core.datamigrator.BulkImageUpload.createWorkbook(BulkImageUpload.java:54) 
at com.atd.core.datamigrator.BulkImageUpload.importImages(BulkImageUpload.java:38) 
at com.atd.core.datamigrator.BulkImageUpload.main(BulkImageUpload.java:236) 

這裏是我的代碼

private Workbook createWorkbook(File file) { 
    File unZipedFile = unZip(file); 
    File[] files = unZipedFile.listFiles(); 
    Workbook wBook = null; 

    for (int i = 0; i < files.length; i++) { 
     if (files[i].getName().contains(".xls")) { 
      try { 
       File f = files[i]; 
       ZipFile zip = new ZipFile(f); 
       wBook = new Workbook(zip); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      break; 
     } 
    } 
    return wBook; 
} 

private File unZip(File input) { 
    File output = new File("unzippedFile"); 
    OutputStream out = null; 
    try { 
     ZipFile zipFile = new ZipFile(input); 
     Enumeration<? extends ZipEntry> entries = zipFile.entries(); 
     while (entries.hasMoreElements()) { 
      ZipEntry entry = entries.nextElement(); 
      File entryDestination = new File(output, entry.getName()); 
      entryDestination.getParentFile().mkdirs(); 
      InputStream in = zipFile.getInputStream(entry); 
      ZipInputStream zis = new ZipInputStream(in); 
      out = new FileOutputStream(entryDestination); 
      out.write(zis.read()); 
      out.flush(); 
      out.close(); 
     } 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return output; 
} 

我知道這是與解壓縮方法的問題,因爲當我使用文件f =新的文件( 「一些路徑」),而不是使用解壓縮的文件,它工作正常。

此外,文件I/O從來不是我的強項,所以是很好:)

+0

arghh。你是我嗎?這正是我前幾天所做的。從@Jon Skeet解答下面的答案。 – tom

回答

2

好了,現在我相信,這就是問題所在:

ZipInputStream zis = new ZipInputStream(in); 
out = new FileOutputStream(entryDestination); 
out.write(zis.read()); 
out.flush(); 
out.close(); 

你創建一個新文件,並寫一個單字節給它。這不會是任何描述的有效Excel文件。您也無法使用finally塊關閉流,但這是另一回事。要複製一個流至另一個的內容,你想要的東西,如:

byte[] buffer = new byte[8192]; 
int bytes; 
while ((bytes = input.read(buffer)) > 0) { 
    output.write(buffer, 0, bytes); 
} 

這就是說,你會更好使用第三方庫來隱藏這一切細節 - 看Guava及其ByteStreams和例如,Files類。

順便說一句,值得回顧一下,弄清楚爲什麼自己沒有發現這個問題。例如,我所做的第一件事就是查看文件解壓縮的目錄,並嘗試打開這些文件。只看到一堆1字節的文件會有點讓人失望。當試圖診斷問題時,至關重要的是你可以將一個大問題分解成小問題,並找出哪一個小問題存在問題。

+0

這樣做,非常感謝! – rearden

相關問題