我可以通过ZipInputStream
,但在开始迭代之前,我想在迭代期间获取我需要的特定文件。我怎样才能做到这一点?从ZipInputStream获取特定文件
ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
{
println entry.getName()
}
我可以通过ZipInputStream
,但在开始迭代之前,我想在迭代期间获取我需要的特定文件。我怎样才能做到这一点?从ZipInputStream获取特定文件
ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
{
println entry.getName()
}
如果myInputStream
你的工作来自磁盘上的真实文件,那么您可以简单地使用java.util.zip.ZipFile
来代替,它由RandomAccessFile
提供支持,并提供按名称直接访问zip条目。但是,如果你拥有的只是一个InputStream
(例如,如果你直接从网络套接字或类似的接收处理流),那么你必须做你自己的缓冲。
您可以在流复制到一个临时文件,然后打开使用ZipFile
该文件,或者如果您知道数据的最大大小提前(例如,对于一个HTTP请求宣告其Content-Length
前面),你可以使用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);
// ....
}
(我还没有测试此代码自己,你可能会发现有必要使用类似的commons-io的CloseShieldInputStream
在bufIn
和第一zipIn
之间,以允许第一压缩数据流,关闭不关闭在你将它倒回之前,底层的bufIn
)。
这正是我的情况。谢谢 – Jils
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;
}
方法'searchImage'缺少返回类型'ZipInputStream'。 – Rooky
使用上的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;
}
}
从Java 7开始,你最好使用而不是ZipStream ZipFile中,如果你只想一个文件,你有一个文件进行读操作:
ZipFile zfile = new ZipFile(aFile);
String myFile = "foo.txt";
ZipEntry entry = zfile.getEntry(myFile);
if (entry) {
// process your file
}
您的第一个代码:请参阅我对tim_yates的回复。 对于你的第二代码:我以为有类似ZipFile的东西。所以对于我的情况应该使用ZipFile。 – Jils
我不明白...迭代条目,直到你得到你想要的,然后处理它? –
首先迭代到文件并按照需要存储它。然后再次迭代。 – Bubletan
也有ZipFile(java <7)和从Java7开始的Zip文件系统(尽管不可能从ZipInputStream :)),这就是为什么这不是对问题的回答 – GPI