是否有可能从zipinputstream获得zipentry的输入流?

我从另一个源接收ZipInputStream,我需要将第一个条目的InputStream提供给另一个源。

我希望能够在不保存设备上的临时文件的情况下执行此操作,但是我知道为单个条目获取InputStream的唯一方法是通过ZipFile.getInputStream(entry),因为我有一个ZipInputStream而不是ZipFile , 这是不可能的。

所以我有最好的解决方案

  1. 将传入的InputStream保存到文件中
  2. 将文件读取为ZipFile
  3. 使用第一个条目的InputStream
  4. 删除临时文件。

想通:

完全有可能,对ZipInputStream.getNextEntry()的调用将InputStream定位在条目的开头,因此提供ZipInputStream相当于提供ZipEntry的InputStream。

ZipInputStream足够聪明,可以处理条目的EOF下游,或者看起来如此。

页。

除了@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。

邮政编码相当简单但我在将ZipInputStream作为Inputstream返回时遇到了问题。 由于某种原因,zip中包含的某些文件会删除字符。 以下是我的解决方案,到目前为止一直在努力。

 private Map getFilesFromZip(final DataHandler dhZ, String operation) throws ServiceFault { Map fileEntries = new HashMap(); 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; }