2016-07-20 132 views
0

我有一個Multipart文件上傳請求。該文件是zip文件 - .zip格式。 我如何解壓這個文件? 我需要爲每個條目的文件路徑和filecontent填充一個Hashmap。.zip文件上傳彈出

HashMap<filepath, filecontent> 

的代碼,我到目前爲止有:

FileInputStream fis = new FileInputStream(zipName); 
ZipInputStream zis = new ZipInputStream(
       new BufferedInputStream(fis)); 
ZipEntry entry; 

while ((entry = zis.getNextEntry()) != null) { 
      int size; 
      byte[] buffer = new byte[2048]; 

      FileOutputStream fos = 
        new FileOutputStream(entry.getName()); 
      BufferedOutputStream bos = 
        new BufferedOutputStream(fos, buffer.length); 

      while ((size = zis.read(buffer, 0, buffer.length)) != -1) { 
       bos.write(buffer, 0, size); 
      } 
      bos.flush(); 
      bos.close(); 
     } 

     zis.close(); 
     fis.close(); 
    } 

回答

1

而不是使用FileOutputStream中的,使用ByteArrayOutputStream捕獲輸出。然後,在對BAOS執行'close'操作之前,使用'toByteArray()'方法將內容作爲字節數組(或使用'toString()')。所以,你的代碼應該是這樣的:

public static HashMap<String, byte[]> test(String zipName) throws Exception { 
    HashMap<String, byte[]> returnValue = new HashMap<>(); 
    FileInputStream fis = new FileInputStream(zipName); 
    ZipInputStream zis = new ZipInputStream(
      new BufferedInputStream(fis)); 
    ZipEntry entry; 

    while ((entry = zis.getNextEntry()) != null) { 

     int size; 
     byte[] buffer = new byte[2048]; 

     ByteArrayOutputStream baos = 
       new ByteArrayOutputStream(); 
     BufferedOutputStream bos = 
       new BufferedOutputStream(baos, buffer.length); 

     while ((size = zis.read(buffer, 0, buffer.length)) != -1) { 
      bos.write(buffer, 0, size); 
     } 
     bos.flush(); 
     bos.close(); 
     returnValue.put(entry.getName(),baos.toByteArray()); 
    } 

    zis.close(); 
    fis.close(); 
    return returnValue; 
}