Java Unzip InputStream unzip(InputStream from, String to, String pattern)

Here you can find the source of unzip(InputStream from, String to, String pattern)

Description

unzip

License

Open Source License

Declaration

private static void unzip(InputStream from, String to, String pattern) 

Method Source Code


//package com.java2s;
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 {
    private static void unzip(InputStream from, String to, String pattern) {
        // System.out.println("from: " + from + " to: " + to + " pattern: " +
        // pattern);
        if (from == null || to == null)
            return;

        try {/*w  w w . ja v a  2s.c  om*/
            ZipInputStream zs = new ZipInputStream(from);
            ZipEntry ze;

            while ((ze = zs.getNextEntry()) != null) {
                String fname = to + '/' + ze.getName();
                // System.out.println(fname);
                boolean match = (pattern == null || ze.getName().matches(pattern));

                if (ze.isDirectory())
                    new File(fname).mkdirs();
                else if (match)
                    externalizeFile(fname, zs);
                else
                    readFile(fname, zs);

                zs.closeEntry();
            }

            zs.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Unable to unpack archive: " + e.getMessage());
        }
    }

    private static File externalizeFile(String fname, InputStream is) throws IOException {
        File f = new File(fname);
        OutputStream out = new FileOutputStream(f);
        byte[] buf = new byte[1024];
        int len;

        while ((len = is.read(buf)) > 0)
            out.write(buf, 0, len);

        out.close();

        return f;
    }

    private static void readFile(String fname, InputStream is) throws IOException {
        File f = new File(fname);
        byte[] buf = new byte[1024];
        int len;

        while ((len = is.read(buf)) > 0)
            ;
    }
}

Related

  1. decompress(InputStream inputStream)
  2. decompress(InputStream is, OutputStream os)
  3. decompressFile(InputStream is, OutputStream os)
  4. decompressStream(InputStream input)
  5. decompressZipArchive(final File zipFile, final File rootDirectoryToUnZip)
  6. unzip(InputStream in)
  7. unzip(InputStream in, File destination)
  8. unzip(InputStream in, File toDir)
  9. unzip(InputStream input, File dest)