I have the contents of a zip file in a byte array. The file contains a number of entries (typically about 12), but I only care about three of them.
I would like to somehow get this into a ZipFile
object, so I can pull those specific three ZipEntry
s out using ZipFile.getEntry
. I'm open to using something other than ZipFile
that has a similar look-up-by-name method like getEntry
.
My initial investigation suggests that I'm out of luck. ZipFile
requires a real file in the file subsystem (which I cannot and do not want to access) and so I can't get there from here, and no means other than ZipFile
exists that allows extracting particular entries by name; but I wanted to check. In languages like C# and Python, this is pretty straightforward (in C# I go from byte array to MemoryStream
to ZipArchive
; in Python I just wrap it in StringIO
and treat like a file), so I wanted to make sure I'm not missing something obvious.
My Plan B is to use ZipInputStream
and repeated calls to getNextEntry
to go through all dozen or so entries, and throw away all except the three I care about, but that just smells bad to me.
A ZipInputStream
can be instantiated for any InputStream
... including a ByteArrayInputStream
.
Apart from that you are out of luck ... if you stick with Java SE classes.
The root of the problem (from an API design perspective) is that ZipFile is a wrapper for functionality that is implemented in native code. The native code opens the input stream for itself, and it uses a native filename / pathname.
The main reason for a native ZIP implementation that works that way is that the JVM needs to load code from ZIP files as part of the bootstrap procedures. This happens before the native implementation has loaded classes such as InputStream
. Indeed, it has to.
There are a number of 3rd party libraries. Start by reading this Q&A - What is a good Java library to zip/unzip files?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.