Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility to unzip an entire archive to a directory in java

Tags:

java

unzip

I'd like to do something like this in my program:

File zipFile = .....;
File destDir = ....;    
ImaginaryZipUtility.unzipAllTo(zipFile, destdir);

I cannot possibly be the first to do this from a program. Where do I find a utility method like above? I tried to look at apache commons-io, but nothing there. So, where should I look?

like image 711
eirikma Avatar asked Aug 31 '10 19:08

eirikma


People also ask

How do I unzip a zip file in Java?

To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.

How do I get files from ZipEntry?

Getting a ZipEntry ZipEntry ). To extract a file from the ZIP file you can call the method getEntry() method on the ZipFile class. Here is an example of calling getEntry() : ZipEntry zipEntry = zipFile.

How can I read the content of a zip file without unzipping it in Java?

Methods. getComment(): String – returns the zip file comment, or null if none. getEntry(String name): ZipEntry – returns the zip file entry for the specified name, or null if not found. getInputStream(ZipEntry entry) : InputStream – Returns an input stream for reading the contents of the specified zip file entry.


2 Answers

Very old code that I was able to dig up

package com.den.frontend;

import java.util.*;
import java.util.zip.*;
import java.io.*;

public class ZIPUtility 
    {
        public static final int BUFFER_SIZE = 2048;

        //This function converts the zip file into uncompressed files which are placed in the 
        //destination directory
        //destination directory should be created first
        public static boolean unzipFiles(String srcDirectory, String srcFile, String destDirectory)
        {
            try
            {
                //first make sure that all the arguments are valid and not null
                if(srcDirectory == null)
                {
                    System.out.println(1);
                    return false;
                }
                if(srcFile == null)
                {
                    System.out.println(2);
                    return false;
                }
                if(destDirectory == null)
                {
                    System.out.println(3);
                    return false;
                }
                if(srcDirectory.equals(""))
                {
                    System.out.println(4);
                    return false;
                }
                if(srcFile.equals(""))
                {   
                    System.out.println(5);
                    return false;
                }
                if(destDirectory.equals(""))
                {
                    System.out.println(6);
                    return false;
                }
                //now make sure that these directories exist
                File sourceDirectory = new File(srcDirectory);
                File sourceFile = new File(srcDirectory + File.separator + srcFile);
                File destinationDirectory = new File(destDirectory);

                // Prevent "Zip Slip" vulnerability https://snyk.io/research/zip-slip-vulnerability
                String canonicalDestinationFile = sourceFile.getCanonicalPath();
                if (!canonicalDestinationFile.startsWith(destinationDirectory.getCanonicalPath() + File.separator)) {
                    throw new Exception("Entry is outside of the target dir: " + e.getName());
                }

                if(!sourceDirectory.exists())
                {
                    System.out.println(7);
                    return false;
                }
                if(!sourceFile.exists())
                {
                    System.out.println(sourceFile);
                    return false;
                }
                if(!destinationDirectory.exists())
                {
                    System.out.println(9);
                    return false;
                }

                //now start with unzip process
                BufferedOutputStream dest = null;

                FileInputStream fis = new FileInputStream(sourceFile);
                ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

                ZipEntry entry = null;

                while((entry = zis.getNextEntry()) != null)
                {
                    String outputFilename = destDirectory + File.separator + entry.getName();

                    System.out.println("Extracting file: " + entry.getName());

                    createDirIfNeeded(destDirectory, entry);

                    int count;

                    byte data[] = new byte[BUFFER_SIZE];

                    //write the file to the disk
                    FileOutputStream fos = new FileOutputStream(outputFilename);
                    dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                    while((count = zis.read(data, 0, BUFFER_SIZE)) != -1)
                    {
                        dest.write(data, 0, count);
                    }

                    //close the output streams
                    dest.flush();
                    dest.close();
                }

                //we are done with all the files
                //close the zip file
                zis.close();

            }
            catch(Exception e)
            {
                e.printStackTrace();
                return false;
            }

            return true;
        }

        private static void createDirIfNeeded(String destDirectory, ZipEntry entry)
        {
            String name = entry.getName();

            if(name.contains("/"))
            {
                System.out.println("directory will need to be created");

                int index = name.lastIndexOf("/");
                String dirSequence = name.substring(0, index);

                File newDirs = new File(destDirectory + File.separator + dirSequence);

                //create the directory
                newDirs.mkdirs();
            }
        }

    }
like image 169
jsshah Avatar answered Oct 19 '22 23:10

jsshah


I know I'm, pretty late to the show, but I was looking for the same thing and found this via google. The easiest way I found is the ant task "unzip". You can use it without any complicated ant setup (there is stuff like ProjectHelper to build a complete ant project) from your java source by including

<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant-compress</artifactId>
    <version>1.2</version>
</dependency>

The code to unzip a file to a directory looks like this

org.apache.ant.compress.taskdefs.Unzip u = new Unzip();
u.setSrc(new File("<archive.zip>"));
u.setDest(new File("<targetDir>"));
u.execute();
like image 21
Philipp Paland Avatar answered Oct 20 '22 00:10

Philipp Paland