Getting specific file from ZipInputStream

Jils picture Jils · Apr 8, 2015 · Viewed 12.1k times · Source

I can go through ZipInputStream, but before starting the iteration I want to get a specific file that I need during the iteration. How can I do that?

ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
 {
    println entry.getName()
}

Answer

Robert Christie picture Robert Christie · Apr 8, 2015

use the getName() method on ZipEntry to get the file you want.

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;
    }
}

From Java 7 onwards, you are better off using ZipFile instead of ZipStream if you only want one file and you have a file to read from:

ZipFile zfile = new ZipFile(aFile);
String myFile = "foo.txt";
ZipEntry entry = zfile.getEntry(myFile);
if (entry) {
     // process your file           
}