2010-07-13 36 views
25

我從另一個源接收ZipInputStream,我需要提供第一入口的的InputStream另一個來源。是有可能從zipinputstream得到的ZipEntry的InputStream的?

我希望能夠做到這一點,而無需在設備上保存臨時文件,但我知道爲單個條目獲取InputStream的唯一方法是通過ZipFile.getInputStream(entry)並且由於我有一個ZipInputStream而不是ZipFile,這是不可能的。

所以最好的解決方案,我已經是

  1. 保存傳入的InputStream文件
  2. 讀取文件的ZipFile
  3. 使用第一入口的InputStream的
  4. 刪除臨時文件。

回答

31

想通:

它是完全可能的,在調用ZipInputStream.getNextEntry()在入口的開始位置的InputStream和因此供給ZipInputStream是供給的ZipEntry的InputStream的等同物。

的ZipInputStream是足夠聰明來處理條目的EOF下游,或者看起來是這樣。

p。

+3

我不明白你的意思嗎?你可以添加一個代碼示例嗎? – Whitecat 2013-01-31 17:08:22

+3

他的意思是ZipInputStream既可以用作整個zip,也可以用於讀取每個組件。 .getNextEntry()進入第一個組件,讀取它,做另一個.getNextEntry(),你的流重置爲第二個組件,等等。實際上很聰明。 – akauppi 2014-08-07 07:21:43

11

除了這裏@pstanton帖子是的代碼的例子。 我使用下面的代碼解決了這個問題。沒有一個例子,很難理解以前的答案。

//If you just want the first file in the zipped InputStream use this code. 
//Otherwise loop through the InputStream using getNextEntry() 
//till you find the file you want. 
private InputStream convertToInputStream(InputStream stream) throws IOException { 
    ZipInputStream zis = new ZipInputStream(stream); 
    zis.getNextEntry(); 
    return zis; 
} 

使用此代碼,您可以返回壓縮文件的InputStream。

+0

在讀完第一個組件之後,可以再次使用'.getNextEntry()'來讀取第二個組件。 – akauppi 2014-08-07 07:22:46

1

該郵政編碼相當簡單,但是我將ZipInputStream作爲InputStream返回時遇到了問題。由於某些原因,zip中包含的一些文件中有字符被丟棄。下面是我的解決方案,迄今爲止它一直在努力。

private Map<String, InputStream> getFilesFromZip(final DataHandler dhZ, 
     String operation) throws ServiceFault { 
    Map<String, InputStream> fileEntries = new HashMap<String, InputStream>(); 
    try { 
     ZipInputStream zipIsZ = new ZipInputStream(dhZ.getDataSource() 
     .getInputStream()); 

     try { 
      ZipEntry entry; 
      while ((entry = zipIsZ.getNextEntry()) != null) { 
       if (!entry.isDirectory()) { 
        Path p = Paths.get(entry.toString()); 
        fileEntries.put(p.getFileName().toString(), 
        convertZipInputStreamToInputStream(zipIsZ)); 
       } 
      } 
     } 
     finally { 
      zipIsZ.close(); 
     } 

    } catch (final Exception e) { 
     faultLocal(LOGGER, e, operation); 
    } 

    return fileEntries; 
} 
private InputStream convertZipInputStreamToInputStream(
final ZipInputStream in) throws IOException { 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    IOUtils.copy(in, out); 
    InputStream is = new ByteArrayInputStream(out.toByteArray()); 
    return is; 
} 
相關問題