我可以通過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