Q:

Java program to read and print all files from a zip file

belongs to collection: Java File Handling Programs

0

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:

  1. getNextEntry() - this will check whether next file (while calling it in the loop) is available in the zip file or not.
  2. getName() - to get file’s name from the zip file.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to get the attributes of a file... >>
<< Java program to check whether a file can be read o...