Java Unzip InputStream unzip(InputStream in, File toDir)

Here you can find the source of unzip(InputStream in, File toDir)

Description

Unzips the given input stream of a ZIP to the given directory

License

Apache License

Declaration

public static void unzip(InputStream in, File toDir) throws IOException 

Method Source Code


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

import java.io.BufferedInputStream;

import java.io.Closeable;
import java.io.File;

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

import java.io.OutputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    /**//from w w  w . ja  va  2s  .co  m
     * Unzips the given input stream of a ZIP to the given directory
     */
    public static void unzip(InputStream in, File toDir) throws IOException {
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in));
        try {
            ZipEntry entry = zis.getNextEntry();
            while (entry != null) {
                if (!entry.isDirectory()) {
                    String entryName = entry.getName();
                    File toFile = new File(toDir, entryName);
                    toFile.getParentFile().mkdirs();
                    OutputStream os = new FileOutputStream(toFile);
                    try {
                        try {
                            copy(zis, os);
                        } finally {
                            zis.closeEntry();
                        }
                    } finally {
                        close(os, true);
                    }
                }
                entry = zis.getNextEntry();
            }
        } finally {
            close(zis, true);
        }
    }

    public static void copy(InputStream is, OutputStream os) throws IOException {
        byte[] b = new byte[4096];
        int l = is.read(b);
        while (l >= 0) {
            os.write(b, 0, l);
            l = is.read(b);
        }
    }

    public static void close(Closeable closeable, boolean swallowIOException) throws IOException {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                if (!swallowIOException) {
                    throw e;
                }
            }
        }
    }
}

Related

  1. decompressStream(InputStream input)
  2. decompressZipArchive(final File zipFile, final File rootDirectoryToUnZip)
  3. unzip(InputStream from, String to, String pattern)
  4. unzip(InputStream in)
  5. unzip(InputStream in, File destination)
  6. unzip(InputStream input, File dest)
  7. unzip(InputStream input, String targetDir)
  8. unzip(InputStream inputStream, String destDirectory)
  9. unzip(InputStream inputStream, String outputFolder)