is it possible to get a zipentry's inputstream from a zipinputstream?

前端 未结 3 809
孤城傲影
孤城傲影 2020-12-10 23:39

I\'m receiving a ZipInputStream from another source, and I need to provide the first entry\'s InputStream to another source.

I was hoping to be able to do this witho

相关标签:
3条回答
  • 2020-12-11 00:36

    In addition to @pstanton post here is an example of code. I solved the problem using the following code. It was difficult to understand what the previous answer without an example.

    //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;
    } 
    

    Using this code you can return an InputStream of the file that is zipped.

    0 讨论(0)
  • 2020-12-11 00:39

    The zip code is fairly easy but I had issues with returning ZipInputStream as Inputstream. For some reason, some of the files contained within the zip had characters being dropped. The below was my solution and so far its been working.

    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;
    }
    
    0 讨论(0)
  • 2020-12-11 00:42

    figured:

    it's entirely possible, the call to ZipInputStream.getNextEntry() positions the InputStream at the start of the entry and therefore supplying the ZipInputStream is the equivalent of supplying a ZipEntry's InputStream.

    the ZipInputStream is smart enough to handle the entry's EOF downstream, or so it seems.

    p.

    0 讨论(0)
提交回复
热议问题