我可以使用ZipInputStream,但在开始迭代之前,我希望获得迭代过程中需要的特定文件。我该怎么做呢?
ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
{
println entry.getName()
}发布于 2015-04-08 22:10:54
如果您正在使用的压缩文件来自磁盘上的真实文件,那么您可以简单地使用java.util.zip.ZipFile,它由一个RandomAccessFile支持,并通过名称提供对myInputStream条目的直接访问。但是如果你所拥有的只是一个InputStream (例如,如果你直接从网络套接字或类似的地方接收到流),那么你就必须自己做缓冲。
您可以将流复制到一个临时文件,然后使用ZipFile打开该文件,或者如果您预先知道数据的最大大小(例如,对于预先声明其Content-Length的HTTP请求),您可以使用BufferedInputStream在内存中对其进行缓冲,直到找到所需的条目。
BufferedInputStream bufIn = new BufferedInputStream(myInputStream);
bufIn.mark(contentLength);
ZipInputStream zipIn = new ZipInputStream(bufIn);
boolean foundSpecial = false;
while ((entry = zin.getNextEntry()) != null) {
if("special.txt".equals(entry.getName())) {
// do whatever you need with the special entry
foundSpecial = true;
break;
}
}
if(foundSpecial) {
// rewind
bufIn.reset();
zipIn = new ZipInputStream(bufIn);
// ....
}(我自己还没有测试过这段代码,您可能会发现有必要在bufIn和第一个zipIn之间使用commons-io CloseShieldInputStream,这样就可以在倒带之前关闭第一个压缩流而不关闭底层bufIn )。
发布于 2015-04-08 21:07:32
在ZipEntry上使用getName()方法来获取所需的文件。
ZipInputStream zin = new ZipInputStream(myInputStream)
String myFile = "foo.txt";
while ((entry = zin.getNextEntry()) != null)
{
if (entry.getName().equals(myFileName)) {
// process your file
// stop looking for your file - you've already found it
break;
}
}从Java7开始,如果您只想要一个文件,并且有一个文件可供读取,那么您最好使用ZipFile而不是ZipStream:
ZipFile zfile = new ZipFile(aFile);
String myFile = "foo.txt";
ZipEntry entry = zfile.getEntry(myFile);
if (entry) {
// process your file
}发布于 2015-04-08 21:07:20
ZipFile file = new ZipFile("file.zip");
ZipInputStream zis = searchImage("foo.png", file);
public searchImage(String name, ZipFile file)
{
for (ZipEntry e : file.entries){
if (e.getName().endsWith(name)){
return file.getInputStream(e);
}
}
return null;
}https://stackoverflow.com/questions/29515348
复制相似问题