Java: extracting a zip file with multiple subdirectories

I have a .zip (Meow.zip) and it has several files and folders like

  • Meow.zip
    • File.txt
    • Program.exe
    • Folder
      • Resource.xml
      • AnotherFolder
        • Otherstuff
          • Learn moreResource.xml

I looked everywhere, but could not find anything. Thanks in advance!

+4
source share
2 answers

Here is a class that decompresses files from a zip file and recreates the directory tree.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ExtractZipContents {

    public static void main(String[] args) {

        try {
            // Open the zip file
            ZipFile zipFile = new ZipFile("Meow.zip");
            Enumeration<?> enu = zipFile.entries();
            while (enu.hasMoreElements()) {
                ZipEntry zipEntry = (ZipEntry) enu.nextElement();

                String name = zipEntry.getName();
                long size = zipEntry.getSize();
                long compressedSize = zipEntry.getCompressedSize();
                System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", 
                        name, size, compressedSize);

                // Do we need to create a directory ?
                File file = new File(name);
                if (name.endsWith("/")) {
                    file.mkdirs();
                    continue;
                }

                File parent = file.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                // Extract the file
                InputStream is = zipFile.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();

            }
            zipFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Source: http://www.avajava.com/tutorials/lessons/how-do-i-unzip-the-contents-of-a-zip-file.html

+4
source

Your friend ZipFile or class ZipInputStrem .

0
source

Source: https://habr.com/ru/post/1542380/


All Articles