Search code examples
javazipinputstream

How to get an InputStream representing one file in a ZipInputStream


I have the following situation:

I am getting a Zip File sent over the network in the Form of a Byte Array. I don't want to save that file locally, but instead target an individual file in that archive and import it into my solution as an InputStream.

Thus far, I have managed to get to the point where I can identify the correct ZipEntry. However, from here all the Zip-tutorials continue by reading the entry by its file name, which naturally does not work in my case since the zip file does not exist locally.

private void InputStream getReqifInputStreamFrom(byte[] reqifzFileBytes){
    ByteArrayInputStream inputStream = new ByteArrayInputStream(reqifzFileBytes);
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry = zipInputStream.getNextEntry();

    while (zipEntry != null) {
        String fileName = zipEntry.getName();
        if (fileName.endsWith(REQIF_FILE_SUFFIX)) {
            return ???;
        }
        zipEntry = zipInputStream.getNextEntry();
    }
}

So, what can I do at that point to return an InputStream that represents exactly the one file that the ZipEntry represents at that point? I have considered just returning the zipInputStream, but since I don't know exactly how that one works I'm afraid that doing so would also include all files that are still in the stream after that file to be returned as well.


Solution

  • You're virtually there. Try

        private InputStream getReqifInputStreamFrom(byte[] reqifzFileBytes) throws IOException {
            InputStream result = null;
            ByteArrayInputStream inputStream = new ByteArrayInputStream(reqifzFileBytes);
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);
            ZipEntry zipEntry = zipInputStream.getNextEntry();
    
            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                if (fileName.endsWith(REQIF_FILE_SUFFIX)) {
                    result = zipInputStream;
                    break;
                }
                zipEntry = zipInputStream.getNextEntry();
            }
            return result;
        }