Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Extracting zip file with multiple subdirectories [duplicate]

Tags:

java

unzip

I have a .zip(Meow.zip) and it has multiple files and folders, like so

  1. Meow.zip
    • File.txt
    • Program.exe
    • Folder
      • Resource.xml
      • AnotherFolder
        • OtherStuff
          • MoreResource.xml

I have looked everywhere but I could not find anything that works. Thanks in advance!

like image 768
user3685130 Avatar asked May 28 '14 19:05

user3685130


2 Answers

Here is a class unzipping files from a zip file and recreating the directory tree as well.

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

like image 128
slaadvak Avatar answered Oct 10 '22 01:10

slaadvak


Your friend is ZipFile or ZipInputStrem class.

like image 26
Aron Lorincz Avatar answered Oct 10 '22 00:10

Aron Lorincz