2011-12-03 69 views
5

我試圖將字節數組轉換爲ZIP文件。怎麼能做到 -如何將字節數組轉換爲ZIP文件

byte[] originalContentBytes= new Verification().readBytesFromAFile(new File("E://file.zip")); 

private byte[] readBytesFromAFile(File file) { 
    int start = 0; 
    int length = 1024; 
    int offset = -1; 
    byte[] buffer = new byte[length]; 
    try { 
     //convert the file content into a byte array 
     FileInputStream fileInuptStream = new FileInputStream(file); 
     BufferedInputStream bufferedInputStream = new BufferedInputStream(
       fileInuptStream); 
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

     while ((offset = bufferedInputStream.read(buffer, start, length)) != -1) { 
      byteArrayOutputStream.write(buffer, start, offset); 
     } 

     bufferedInputStream.close(); 
     byteArrayOutputStream.flush(); 
     buffer = byteArrayOutputStream.toByteArray(); 
     byteArrayOutputStream.close(); 
    } catch (FileNotFoundException fileNotFoundException) { 
     fileNotFoundException.printStackTrace(); 
    } catch (IOException ioException) { 
     ioException.printStackTrace(); 
    } 

    return buffer; 
} 

但現在我的問題是字節數​​組轉換回一個ZIP文件:我用下面的代碼有個字節?

注意:指定的ZIP包含兩個文件。

+0

你究竟想要什麼?你想把字節寫回磁盤到一個zip文件中嗎?或者你想閱讀內容?你讀取它們的字節還沒有被解碼。 – morja

+0

@ morja - >是的,我想以壓縮文件的形式將字節寫回磁盤。 – Mohan

+0

好吧,但只需用FileOutputStream將字節寫回磁盤並命名文件.zip即可。你不想寫提取的文件? – morja

回答

17

要獲得從字節的內容,你可以使用

ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes)); 
ZipEntry entry = null; 
while ((entry = zipStream.getNextEntry()) != null) { 

    String entryName = entry.getName(); 

    FileOutputStream out = new FileOutputStream(entryName); 

    byte[] byteBuff = new byte[4096]; 
    int bytesRead = 0; 
    while ((bytesRead = zipStream.read(byteBuff)) != -1) 
    { 
     out.write(byteBuff, 0, bytesRead); 
    } 

    out.close(); 
    zipStream.closeEntry(); 
} 
zipStream.close(); 
+0

你可以幫助我獲得zip文件中的條目名稱。使用這個我們只能讀取內容。但我們如何將其存儲到磁盤。 – Mohan

+0

您可以從zipStream中讀取字節,然後使用FileOutputStream將其寫入。或者直接再寫出來。查看我的更新。 – morja

+0

非常感謝,它非常完美。 – Mohan

5

你可能正在尋找這樣的代碼:

ZipInputStream z = new ZipInputStream(new ByteArrayInputStream(buffer)) 

現在你可以通過getNextEntry()

獲得的zip文件內容
相關問題