Java Unzip File unzip(File file, String targetDirectory)

Here you can find the source of unzip(File file, String targetDirectory)

Description

unzip

License

Apache License

Declaration

public static void unzip(File file, String targetDirectory) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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 {
    public static void unzip(File file, String targetDirectory) throws Exception {

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

        ZipFile zipFile = new ZipFile(file);
        Enumeration<?> entries = zipFile.entries();

        String stripName = file.getName();
        int i = stripName.lastIndexOf('.');
        if (i > 0) {
            stripName = stripName.substring(0, i);
        }/*from  w  ww. j  a  v a  2  s. co  m*/

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

            String entryName = entry.getName();

            if (entryName.startsWith(stripName + "/") || entryName.startsWith(stripName + "\\")) {
                entryName = entryName.substring(stripName.length() + 1);
            }

            if (entry.isDirectory()) {
                File dir = new File(targetDirectory, entryName);
                dir.mkdirs();
                continue;
            }
            copyInputStream(zipFile.getInputStream(entry),
                    new BufferedOutputStream(new FileOutputStream(new File(targetDirectory, entryName))));
        }
        zipFile.close();
    }

    public static 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 file, File targetDirectory)
  2. unzip(File file, File toDir)
  3. unzip(File file, File toDirectory)
  4. unzip(File file, String destination, String container)
  5. unZip(File file, String outPath, String zipFileName)
  6. unzip(File fileToUnzip, File destinationDirectory)
  7. unZip(File inFile, File unzipDir)
  8. unzip(File input)
  9. unzip(File input, File outputDir)