zip
Search file in a zip file
This is an example of how to search a File in a zip file, using the ZipFile class. Searching a File in a zip file implies that you should:
- Create a new ZipFile and open it for reading.
- Get the enumeration of the ZipFile entries, with
entries()API method of ZipFile and iterate through each one of them. - For each one of the entries, get its name, with
getName()API method of ZipEntry. - If the name is equal to the name of the file we are searching, then return true, else false.
- Close the ZipFile, with
close()API method of ZipFile.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class SearchFileInAZipFile {
public static void main(String[] args) {
String searchFile = "seek.txt";
ZipFile zipFile = null;
boolean fileFound = false;
try {
// open a zip file for reading
zipFile = new ZipFile("c:/archive.zip");
// get an enumeration of the ZIP file entries
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
// get the name of the entry
String entryName = entry.getName();
if (entryName.equalsIgnoreCase(searchFile)) {
fileFound = true;
break;
}
}
}
catch (IOException ioe) {
System.out.println("Error opening zip file" + ioe);
}
finally {
try {
if (zipFile!=null) {
zipFile.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing zip file" + ioe);
}
}
System.out.println("File found: " + fileFound);
}
}
This was an example of how to search a File in a zip file in Java.

