Java Unzip InputStream unzip(InputStream source, File target)

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

Description

unzip

License

Open Source License

Parameter

Parameter Description
source zip stream
target target directory

Exception

Parameter Description
IOException extraction failed

Declaration

public static void unzip(InputStream source, File target) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from ww w .j  a v  a2 s.com
     * @param source zip stream
     * @param target target directory
     * @throws IOException extraction failed
     */
    public static void unzip(InputStream source, File target) throws IOException {

        final ZipInputStream zipStream = new ZipInputStream(source);
        ZipEntry nextEntry;
        while ((nextEntry = zipStream.getNextEntry()) != null) {
            final String name = nextEntry.getName();
            // only extract files
            if (!name.endsWith("/")) {
                final File nextFile = new File(target, name);

                // create directories
                final File parent = nextFile.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                // write file
                try (OutputStream targetStream = new FileOutputStream(nextFile)) {
                    copy(zipStream, targetStream);
                }
            }
        }
    }

    private static void copy(final InputStream source, final OutputStream target) throws IOException {

        final int bufferSize = 4 * 1024;
        final byte[] buffer = new byte[bufferSize];

        int nextCount;
        while ((nextCount = source.read(buffer)) >= 0) {
            target.write(buffer, 0, nextCount);
        }
    }
}

Related

  1. unzip(InputStream input, String targetDir)
  2. unzip(InputStream inputStream, String destDirectory)
  3. unzip(InputStream inputStream, String outputFolder)
  4. unzip(InputStream is, File destDir)
  5. unzip(InputStream libInputStream, String path)
  6. unzip(InputStream zin, File file)