简体   繁体   English

Java:从字节数组获取ZipFile的任何方法(或带有直接getEntry方法的任何方法)?

[英]Java: any way to get a ZipFile (or anything with a direct getEntry method) from a byte array?

I have the contents of a zip file in a byte array. 我在字节数组中有一个zip文件的内容。 The file contains a number of entries (typically about 12), but I only care about three of them. 该文件包含许多条目(通常约为12个),但我只关心其中的三个。

I would like to somehow get this into a ZipFile object, so I can pull those specific three ZipEntry s out using ZipFile.getEntry . 我想以某种方式将其放入ZipFile对象,以便可以使用ZipFile.getEntry三个特定的ZipEntry取出。 I'm open to using something other than ZipFile that has a similar look-up-by-name method like getEntry . 我愿意使用ZipFile以外的其他东西,这些东西具有类似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; ZipFile需要文件子系统中的真实文件(我不能也不想访问),所以我不能从这里到达那里,除了ZipFile之外,没有其他方法可以按名称提取特定条目。 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. 在C#和Python之类的语言中,这非常简单(在C#中,我从字节数组转到MemoryStreamZipArchive ;在Python中,我只是将其包装在StringIO并像一个文件一样对待),所以我想确保自己不会丢失明显的东西。

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. 我的计划B是使用ZipInputStream并重复调用getNextEntry以遍历所有十几个条目,并丢弃所有我不在乎的条目,但这对我来说很不好。

A ZipInputStream can be instantiated for any InputStream ... including a ByteArrayInputStream . 可以为任何InputStream实例化ZipInputStream ,包括ByteArrayInputStream

Apart from that you are out of luck ... if you stick with Java SE classes. 除此之外,如果您坚持使用Java SE类,那么您会不走运。

The root of the problem (from an API design perspective) is that ZipFile is a wrapper for functionality that is implemented in native code. 问题的根源(从API设计的角度来看)是ZipFile是使用本机代码实现的功能的包装。 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. 能够以这种方式工作的本机ZIP实现的主要原因是,JVM需要作为引导过程的一部分从ZIP文件中加载代码。 This happens before the native implementation has loaded classes such as InputStream . 这是本机实现加载诸如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? 从阅读此问答开始- 什么是压缩/解压缩文件的良好Java库?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM