List or display contents of compressed or zipped file in java (example)

  • Given a zipped or compressed file in java.
  • We would like to display or list the contents of zipped file.
    • We will display the name and size of uncompressed files.

Program – list or display contents of zipped /compressed file in java

package org.learn;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class DisplayZipContents {
    public static void main(String[] args) throws IOException {

        ZipFile inputZipFile = new ZipFile("C:\\output\\zipDirectory.zip");
        System.out.printf("1.Displaying contents of input directory: %s\n\n",
                                                        inputZipFile.getName());
        final Enumeration<? extends ZipEntry> zipFiles = inputZipFile.entries();
        int nFile = 2;
        while(zipFiles.hasMoreElements()) {
            ZipEntry zipEntry = zipFiles.nextElement();
            long fileSize = zipEntry.getCompressedSize();
            String fileName = zipEntry.getName();
            System.out.printf("%d. File Name: %s, File size = %d bytes\n",nFile++, fileName, fileSize);
        }
    }
}

Output – list or display contents of zipped / compressed file in java

1.Displaying contents of input directory: C:\output\zipDirectory.zip

2. File Name: Dir1/Dir1_F1.txt, File size = 18 bytes
3. File Name: Dir1/Dir1_F2.txt, File size = 20 bytes
4. File Name: Dir1/Dir11/Dir11_F1.txt, File size = 18 bytes
5. File Name: Dir1/Dir11/Dir11_F2.txt, File size = 20 bytes
6. File Name: Dir2/Dir2_F1.txt, File size = 18 bytes
7. File Name: Dir2/Dir2_F2.txt, File size = 20 bytes
8. File Name: Dir2/Dir21/Dir21_F1.txt, File size = 18 bytes
9. File Name: Dir2/Dir21/Dir21_F2.txt, File size = 20 bytes
10. File Name: FirstFile.txt, File size = 18 bytes
11. File Name: SecondFile.txt, File size = 20 bytes
12. File Name: ThirdFile.txt, File size = 19 bytes
Scroll to Top