Home »
Java Programs »
Java File Handling Programs
Java program to read and print all files from a zip file
In this java program, we are going to learn how to read a zip file and access all files from it? Here, we will have a zip file, read files from it and print file names.
Submitted by IncludeHelp, on November 03, 2017
Given a zip file, and we have to print all files names from it using java program.
To implement this java program, we are going to use main classes FileInputStream to manage normal files by creating its object, and ZipInputStream to manage zip files by creating its object.
There are two other methods of ZipInputStream class, which are:
- getNextEntry() - this will check whether next file (while calling it in the loop) is available in the zip file or not.
- getName() - to get file’s name from the zip file.
Program to extract the names of files from zip file in java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class FindFileInZipFile {
public void printFileList(String filePath) {
// initializing the objects.
FileInputStream fis = null;
ZipInputStream Zis = null;
ZipEntry zEntry = null;
try {
fis = new FileInputStream(filePath);
Zis = new ZipInputStream(new BufferedInputStream(fis));
// this will search the files while end of the zip.
while ((zEntry = Zis.getNextEntry()) != null) {
System.out.println(zEntry.getName());
}
Zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//main function
public static void main(String a[]) {
// creating object of the file.
FindFileInZipFile fff = new FindFileInZipFile();
System.out.println("Files in the Zip are : ");
// enter the path of the zip file with name.
fff.printFileList("D:/JAVA.zip");
}
}
Output
Files in the Zip are :
ExOops.java
Java File Handling Programs »