2016-02-26 80 views
0

我有一個名爲「MyApp」的項目。 MyApp將使用我創建的一個名爲「MyLibrary」的Java庫。我在「MyLibrary」中編寫了一個函數,用於解壓縮「MyApp」中的zip文件(或任何應用程序使用「MyLibrary」)「resources」dir。如何從非物理文件創建zip文件?

閱讀https://community.oracle.com/blogs/kohsuke/2007/04/25/how-convert-javaneturl-javaiofile我無法通過路徑創建文件,因爲它不是「物理文件」。我使用zip4j,但它的構造函數使用File或String而不是InputStream。所以,我不能做到這一點:

ZipFile zipfile = new  
     ZipFile("src/main/resources/compressed.zip"); 
downloadedZipfile.extractAll("src/main/resources"); 

java.io.File的javadoc和http://www.mkyong.com/java/how-to-convert-inputstream-to-file-in-java/表示沒有辦法的InputStream轉換成文件。

是否有另一種方式來訪問使用我的庫的項目中的zip文件?先謝謝你。

UPDATE: zipIn缺少條目,所以while循環不會提取文件。

InputStream in = getInputStream("", JSON_FILENAME); 
    ZipInputStream zipIn = new ZipInputStream(in); 

    ZipEntry entry; 
    try { 
     while ((entry = zipIn.getNextEntry()) != null) { 
      String filepath = entry.getName(); 
      if(!entry.isDirectory()) { 
       extractFile(zipIn, filepath); 
      } 
      else { 
       File dir = new File(filepath); 
       dir.mkdir(); 
      } 
      zipIn.closeEntry(); 
     } 
     zipIn.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

private void extractFile(ZipInputStream zipIn, String filepath) { 
    BufferedOutputStream bos = null; 
    try { 
     bos = new BufferedOutputStream(new FileOutputStream(filepath)); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    byte[] bytesIn = new byte[BUFFER_SIZE]; 
    int read = 0; 
    try { 
     while ((read = zipIn.read(bytesIn)) != -1) { 
      bos.write(bytesIn, 0, read); 
     } 
     bos.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

會將文件使用此代碼屬於「在MyLibrary」時,可以提取到「MyApp的」主目錄?

+0

。 https://truezip.java.net/ – Marged

+0

在您的應用程序的jar文件中訪問文件通常由'Class.getResourceAsStream'完成https://docs.oracle.com/javase/7/docs/api/java/lang /Class.html#getResourceAsStream(java.lang.String) – njzk2

回答

2

如果你有InputStream到您的虛擬ZIP文件,您可以使用java.util.zip.ZipInputStream讀取ZIP條目:雖然我相當肯定zip4j將支持類似的東西我可以告訴你,truezip確實爲確保

InputStream in = ... 
ZipInputStream zipIn = new ZipInputStream(in); 

ZipEntry entry; 
while ((entry = zipIn.getNextEntry()) != null) { 
    // handle the entry 
} 
+0

第一行可能使用[Class.getResourceAsStream](https://docs.oracle.com/javase/8/docs/api/java/lang/Class的.html#的getResourceAsStream-java.lang.String-)。例如,'InputStream in = WhateverClassContainsThisCode.class.getResourceAsStream(「/ compressed.zip」);' – VGR

+0

我驗證了我的InputStream是正確的,但getNextEntry爲null,你能檢查上面的代碼嗎?提取的文件位於何處?謝謝 – Marc

+0

@Marc while循環很好。 (測試:通過使用來自現有壓縮文件的'InputStream'運行片段)。否則,通過將其保存到文件並使用ZipFile打開該文件來驗證「InputStream」 – wero