Java Unzip File unzip(File srcZipFile, File tgtDir)

Here you can find the source of unzip(File srcZipFile, File tgtDir)

Description

Unzips the contents of a zip file to a directory

License

Open Source License

Parameter

Parameter Description
zipfile source zip file
tgtDir target directory

Declaration

public static boolean unzip(File srcZipFile, File tgtDir) 

Method Source Code

//package com.java2s;
// are made available under the terms of the Eclipse Public License v1.0

import java.io.BufferedOutputStream;
import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main {
    /**/* w  w w  .ja v a2s .  com*/
     * Unzips the contents of a zip file to a directory
     * 
     * @param zipfile
     *            source zip file
     * @param tgtDir
     *            target directory
     */
    public static boolean unzip(File srcZipFile, File tgtDir) {
        if (!srcZipFile.exists() || !tgtDir.exists()) {
            return false;
        }

        if (!tgtDir.isDirectory()) {
            return false;
        }

        try {
            ZipFile zipFile = new ZipFile(srcZipFile);
            Enumeration entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();

                File tgtFile = new File(tgtDir, entry.getName());

                if (entry.isDirectory() && !tgtFile.exists()) {
                    tgtFile.mkdirs();

                } else {
                    File parentFolder = tgtFile.getParentFile();
                    if (!parentFolder.exists()) {
                        parentFolder.mkdirs();
                    }

                    copyInputStream(zipFile.getInputStream(entry),
                            new BufferedOutputStream(new FileOutputStream(new File(tgtDir, entry.getName()))));
                }
            }

            zipFile.close();
        } catch (IOException ioe) {
            return false;
        }
        return false;
    }

    private static final void copyInputStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int len;

        while ((len = in.read(buffer)) >= 0)
            out.write(buffer, 0, len);

        in.close();
        out.close();
    }
}

Related

  1. unzip(File jarFile, File destDir)
  2. unzip(File sourceFile, File rootDir)
  3. unzip(File sourceZipfile, File directory)
  4. unzip(File src, File dest)
  5. unzip(File src, File target)
  6. unzip(File tarFile, File destinationDir)
  7. unzip(File target)
  8. unzip(File targetZip, File dirToExtract)
  9. unzip(File zip)