I can go through ZipInputStream
, but before starting the iteration I want to get a specific file that I need during the iteration. How can I do that?
ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
{
println entry.getName()
}
Look at Finding a file in zip entry
use the getName() method on ZipEntry to get the file you want.
From Java 7 onwards, you are better off using ZipFile instead of ZipStream if you only want one file and you have a file to read from:
If the
myInputStream
you're working with comes from a real file on disk then you can simply usejava.util.zip.ZipFile
instead, which is backed by aRandomAccessFile
and provides direct access to the zip entries by name. But if all you have is anInputStream
(e.g. if you're processing the stream directly on receipt from a network socket or similar) then you'll have to do your own buffering.You could copy the stream to a temporary file, then open that file using
ZipFile
, or if you know the maximum size of the data in advance (e.g. for an HTTP request that declares itsContent-Length
up front) you could use aBufferedInputStream
to buffer it in memory until you've found the required entry.(I haven't tested this code myself, you may find it's necessary to use something like the commons-io
CloseShieldInputStream
in between thebufIn
and the firstzipIn
, to allow the first zip stream to close without closing the underlyingbufIn
before you've rewound it).