<p>I am trying to read a single file from a <code>java.util.zip.ZipInputStream</code>, and copy it into a <code>java.io.ByteArrayOutputStream</code> (so that I can then create a <code>java.io.ByteArrayInputStream</code> and hand that to a 3rd party library that will end up closing the stream, and I don't want my <code>ZipInputStream</code> getting closed).</p>

<p>I'm probably missing something basic here, but I never enter the while loop here:</p>

<pre><code>ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();
int bytesRead;
byte[] tempBuffer = new byte[8192*2];
try {
    while ((bytesRead = zipStream.read(tempBuffer)) != -1) {
        streamBuilder.write(tempBuffer, 0, bytesRead);
    }
} catch (IOException e) {
    // ...
}
</code></pre>

<p>What am I missing that will allow me to copy the stream?</p>

<p><strong>Edit:</strong></p>

<p>I should have mentioned earlier that this <code>ZipInputStream</code> is not coming from a file, so I don't think I can use a <code>ZipFile</code>. It is coming from a file uploaded through a servlet.</p>

<p>Also, I have already called <code>getNextEntry()</code> on the <code>ZipInputStream</code> before getting to this snippet of code. If I don't try copying the file into another <code>InputStream</code> (via the <code>OutputStream</code> mentioned above), and just pass the <code>ZipInputStream</code> to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.</p>

[{'answer_id': 67367, 'author': 'Sunny Milenov', 'author_id': 8220, 'author_profile': 'https://Stackoverflow.com/users/8220', 'pm_score': -1, 'selected': False, 'text': '<p>Check if the input stream is positioned in the begging.</p>\n\n<p>Otherwise, as implementation: I do not think that you need to write to the result stream while you are reading, unless you process this exact stream in another thread.</p>\n\n<p>Just create a byte array, read the input stream, then create the output stream.</p>\n'}, {'answer_id': 67377, 'author': 'Boris Bokowski', 'author_id': 10114, 'author_profile': 'https://Stackoverflow.com/users/10114', 'pm_score': 0, 'selected': False, 'text': '<p>It is unclear how you got the zipStream. It should work when you get it like this:</p>\n\n<pre><code>  zipStream = zipFile.getInputStream(zipEntry)\n</code></pre>\n'}, {'answer_id': 67403, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d use <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html" rel="nofollow noreferrer">IOUtils</a> from the commons io project.</p>\n\n<pre><code>IOUtils.copy(zipStream, byteArrayOutputStream);\n</code></pre>\n'}, {'answer_id': 67719, 'author': 'Benedikt Waldvogel', 'author_id': 4308, 'author_profile': 'https://Stackoverflow.com/users/4308', 'pm_score': 3, 'selected': False, 'text': '<p>You probably tried reading from a <code>FileInputStream</code> like this:</p>\n\n<pre><code>ZipInputStream in = new ZipInputStream(new FileInputStream(...));</code></pre>\n\n<p>This <strong>won’t</strong> work since a zip archive can contain multiple files and you need to specify which file to read.</p>\n\n<p>You could use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/zip/ZipFile.html" rel="nofollow noreferrer">java.util.zip.ZipFile</a> and a library such as <a href="https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html" rel="nofollow noreferrer">IOUtils from Apache Commons IO</a> or <a href="https://google.github.io/guava/releases/21.0/api/docs/com/google/common/io/ByteStreams.html" rel="nofollow noreferrer">ByteStreams from Guava</a> that assist you in copying the stream.</p>\n\n<p>Example:</p>\n\n<pre><code>ByteArrayOutputStream out = new ByteArrayOutputStream();\ntry (ZipFile zipFile = new ZipFile("foo.zip")) {\n    ZipEntry zipEntry = zipFile.getEntry("fileInTheZip.txt");\n\n    try (InputStream in = zipFile.getInputStream(zipEntry)) {\n        IOUtils.copy(in, out);\n    }\n}\n</code></pre>\n'}, {'answer_id': 67765, 'author': 'helios', 'author_id': 9686, 'author_profile': 'https://Stackoverflow.com/users/9686', 'pm_score': 0, 'selected': False, 'text': '<p>t is unclear how you got the zipStream. It should work when you get it like this:</p>\n\n<pre><code>  zipStream = zipFile.getInputStream(zipEntry)\n</code></pre>\n\n<p>If you are obtaining the ZipInputStream from a ZipFile you can get one stream for the 3d party library, let it use it, and you obtain another input stream using the code before.</p>\n\n<p>Remember, an inputstream is a cursor. If you have the entire data (like a ZipFile) you can ask for N cursors over it.</p>\n\n<p>A diferent case is if you only have an "GZip" inputstream, only an zipped byte stream. In that case you ByteArrayOutputStream buffer makes all sense.</p>\n'}, {'answer_id': 68187, 'author': 'Boris Bokowski', 'author_id': 10114, 'author_profile': 'https://Stackoverflow.com/users/10114', 'pm_score': 1, 'selected': False, 'text': '<p>I would call getNextEntry() on the ZipInputStream until it is at the entry you want (use ZipEntry.getName() etc.).  Calling getNextEntry() will advance the "cursor" to the beginning of the entry that it returns.  Then, use ZipEntry.getSize() to determine how many bytes you should read using zipInputStream.read().</p>\n'}, {'answer_id': 69177, 'author': 'jt.', 'author_id': 4362, 'author_profile': 'https://Stackoverflow.com/users/4362', 'pm_score': 2, 'selected': False, 'text': '<p>You could implement your own wrapper around the ZipInputStream that ignores close() and hand that off to the third-party library.</p>\n\n<pre><code>thirdPartyLib.handleZipData(new CloseIgnoringInputStream(zipStream));\n\n\nclass CloseIgnoringInputStream extends InputStream\n{\n    private ZipInputStream stream;\n\n    public CloseIgnoringInputStream(ZipInputStream inStream)\n    {\n        stream = inStream;\n    }\n\n    public int read() throws IOException {\n        return stream.read();\n    }\n\n    public void close()\n    {\n        //ignore\n    }\n\n    public void reallyClose() throws IOException\n    {\n        stream.close();\n    }\n}\n</code></pre>\n'}, {'answer_id': 69489, 'author': 'Kevin Day', 'author_id': 10973, 'author_profile': 'https://Stackoverflow.com/users/10973', 'pm_score': 4, 'selected': True, 'text': "<p>Your loop looks valid - what does the following code (just on it's own) return?</p>\n\n<pre><code>zipStream.read(tempBuffer)\n</code></pre>\n\n<p>if it's returning -1, then the zipStream is closed before you get it, and all bets are off.  It's time to use your debugger and make sure what's being passed to you is actually valid.</p>\n\n<p>When you call getNextEntry(), does it return a value, and is the data in the entry meaningful (i.e. does getCompressedSize() return a valid value)?  IF you are just reading a Zip file that doesn't have read-ahead zip entries embedded, then ZipInputStream isn't going to work for you.</p>\n\n<p>Some useful tidbits about the Zip format:</p>\n\n<p>Each file embedded in a zip file has a header.  This header can contain useful information (such as the compressed length of the stream, it's offset in the file, CRC) - or it can contain some magic values that basically say 'The information isn't in the stream header, you have to check the Zip post-amble'.</p>\n\n<p>Each zip file then has a table that is attached to the end of the file that contains all of the zip entries, along with the real data.  The table at the end is mandatory, and the values in it must be correct.  In contrast, the values embedded in the stream do not have to be provided.</p>\n\n<p>If you use ZipFile, it reads the table at the end of the zip.  If you use ZipInputStream, I suspect that getNextEntry() attempts to use the entries embedded in the stream.  If those values aren't specified, then ZipInputStream has no idea how long the stream might be.  The inflate algorithm is self terminating (you actually don't need to know the uncompressed length of the output stream in order to fully recover the output), but it's possible that the Java version of this reader doesn't handle this situation very well.</p>\n\n<p>I will say that it's fairly unusual to have a servlet returning a ZipInputStream (it's much more common to receive an inflatorInputStream if you are going to be receiving compressed content.</p>\n"}, {'answer_id': 2093184, 'author': 'Dmytro ', 'author_id': 253962, 'author_profile': 'https://Stackoverflow.com/users/253962', 'pm_score': 0, 'selected': False, 'text': '<p>Please try code bellow</p>\n\n<pre><code>private static byte[] getZipArchiveContent(File zipName) throws WorkflowServiceBusinessException {\n\n  BufferedInputStream buffer = null;\n  FileInputStream fileStream = null;\n  ByteArrayOutputStream byteOut = null;\n  byte data[] = new byte[BUFFER];\n\n  try {\n   try {\n    fileStream = new FileInputStream(zipName);\n    buffer = new BufferedInputStream(fileStream);\n    byteOut = new ByteArrayOutputStream();\n\n    int count;\n    while((count = buffer.read(data, 0, BUFFER)) != -1) {\n     byteOut.write(data, 0, count);\n    }\n   } catch(Exception e) {\n    throw new WorkflowServiceBusinessException(e.getMessage(), e);\n   } finally {\n    if(null != fileStream) {\n     fileStream.close();\n    }\n    if(null != buffer) {\n     buffer.close();\n    }\n    if(null != byteOut) {\n     byteOut.close();\n    }\n   }\n  } catch(Exception e) {\n   throw new WorkflowServiceBusinessException(e.getMessage(), e);\n  }\n  return byteOut.toByteArray();\n\n }\n</code></pre>\n'}, {'answer_id': 9999404, 'author': 'Juan Ignacio', 'author_id': 1311188, 'author_profile': 'https://Stackoverflow.com/users/1311188', 'pm_score': 2, 'selected': False, 'text': "<p>You're missing call</p>\n\n<p>ZipEntry entry = (ZipEntry) zipStream.getNextEntry(); </p>\n\n<p>to position the first byte decompressed of the first entry.</p>\n\n<pre><code> ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream();\n int bytesRead;\n byte[] tempBuffer = new byte[8192*2];\n ZipEntry entry = (ZipEntry) zipStream.getNextEntry();\n try {\n     while ( (bytesRead = zipStream.read(tempBuffer)) != -1 ){\n        streamBuilder.write(tempBuffer, 0, bytesRead);\n     }\n } catch (IOException e) {\n      ...\n }\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/67275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4257/']