Example usage for java.util.zip ZipInputStream ZipInputStream

List of usage examples for java.util.zip ZipInputStream ZipInputStream

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream ZipInputStream.

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:aurelienribon.gdxsetupui.ProjectUpdate.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * correct folders of the projects./*from ww  w  . jav  a2s  . co  m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(Helper.getCorePrjPath(cfg) + "libs");
    File desktopPrjLibsDir = new File(Helper.getDesktopPrjPath(cfg) + "libs");
    File androidPrjLibsDir = new File(Helper.getAndroidPrjPath(cfg) + "libs");
    File htmlPrjLibsDir = new File(Helper.getHtmlPrjPath(cfg) + "war/WEB-INF/lib");
    File iosPrjLibsDir = new File(Helper.getIosPrjPath(cfg) + "libs");
    File dataDir = new File(Helper.getAndroidPrjPath(cfg) + "assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);

            if (cfg.isDesktopIncluded) {
                for (String elemName : def.libsDesktop)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, desktopPrjLibsDir);
            }

            if (cfg.isAndroidIncluded) {
                for (String elemName : def.libsAndroid)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, androidPrjLibsDir);
                for (String elemName : def.data)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, dataDir);
            }

            if (cfg.isHtmlIncluded) {
                for (String elemName : def.libsHtml)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, htmlPrjLibsDir);
            }

            if (cfg.isIosIncluded) {
                for (String elemName : def.libsIos)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, iosPrjLibsDir);
            }
        }

        zis.close();
    }
}

From source file:br.com.ingenieux.mojo.jbake.SeedMojo.java

private void unpackZip(File tmpZipFile) throws IOException {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(tmpZipFile));
    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        if (ze.isDirectory()) {
            ze = zis.getNextEntry();/*from ww w .j  a  va 2s .  co  m*/
            continue;
        }

        String fileName = stripLeadingPath(ze.getName());
        File newFile = new File(outputDirectory + File.separator + fileName);

        new File(newFile.getParent()).mkdirs();

        FileOutputStream fos = new FileOutputStream(newFile);

        IOUtils.copy(zis, fos);

        fos.close();
        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Un zip a file to a destination folder.
 * @param zipFile the zip file/* w ww .ja  v a 2  s. c o  m*/
 * @param outputFolder the output folder
 */
public static void unZipFile(final String zipFile, final String outputFolder) {

    LogUtil.setLogString("UnZip the File", true);
    final byte[] buffer = new byte[1024];
    int len;
    try {
        // create output directory is not exists
        final File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        // get the zip file content
        final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        final StringBuilder outFolderPath = new StringBuilder();
        final StringBuilder fileLogPath = new StringBuilder();
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
            final String fileName = zipEntry.getName();
            final File newFile = new File(
                    outFolderPath.append(outputFolder).append(File.separator).append(fileName).toString());
            LogUtil.setLogString(
                    fileLogPath.append("file unzip : ").append(newFile.getAbsoluteFile()).toString(), true);
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            final FileOutputStream fos = new FileOutputStream(newFile);

            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            fileLogPath.setLength(0);
            outFolderPath.setLength(0);
        }

        zis.closeEntry();
        zis.close();

        LogUtil.setLogString("Done", true);

    } catch (IOException ex) {
        LOGGER.error("Error in unzip file", ex);
    }
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//from   w w w .  j  a  va 2 s. co  m

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

                String mime = new Tika().detect(newFile);
                if (mime.equals("application/x-sh") || mime.startsWith("text/"))
                    FileUtils.writeLines(newFile, FileUtils.readLines(newFile));

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.khubla.simpleioc.classlibrary.ClassLibrary.java

/**
 * find all the classes in a jar file//from  w  ww. j  a  va2s.  co m
 */
private List<Class<?>> crackJar(String jarfile) throws Exception {
    try {
        /*
         * the ret
         */
        final List<Class<?>> ret = new ArrayList<Class<?>>();
        /*
         * the jar
         */
        final FileInputStream fis = new FileInputStream(jarfile);
        final ZipInputStream zip_inputstream = new ZipInputStream(fis);
        ZipEntry current_zip_entry = null;
        while ((current_zip_entry = zip_inputstream.getNextEntry()) != null) {
            if (current_zip_entry.getName().endsWith(".class")) {
                if (current_zip_entry.getSize() > 0) {
                    final ClassNode classNode = new ClassNode();
                    final ClassReader cr = new ClassReader(zip_inputstream);
                    cr.accept(classNode, 0);
                    if (annotated(classNode)) {
                        ret.add(Class.forName(classNode.name.replaceAll("/", ".")));
                        log.debug("Found " + classNode.name + " in " + jarfile);
                    }
                }
            }
        }
        zip_inputstream.close();
        fis.close();
        return ret;
    } catch (final Throwable e) {
        throw new Exception("Exception in crackJar for jar '" + jarfile + "'", e);
    }
}

From source file:com.marklogic.contentpump.CompressedAggXMLReader.java

protected void initStreamReader(InputSplit inSplit) throws IOException, InterruptedException {
    setFile(((FileSplit) inSplit).getPath());
    FSDataInputStream fileIn = fs.open(file);
    String codecString = conf.get(ConfigConstants.CONF_INPUT_COMPRESSION_CODEC,
            CompressionCodec.ZIP.toString());
    if (codecString.equalsIgnoreCase(CompressionCodec.ZIP.toString())) {
        zipIn = new ZipInputStream(fileIn);
        codec = CompressionCodec.ZIP;// ww  w  . j  a  va 2  s.  c o m
        while (true) {
            try {
                currZipEntry = ((ZipInputStream) zipIn).getNextEntry();
                if (currZipEntry == null) {
                    break;
                }
                if (currZipEntry.getSize() != 0) {
                    subId = currZipEntry.getName();
                    break;
                }
            } catch (IllegalArgumentException e) {
                LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage());
            }
        }
        if (currZipEntry == null) { // no entry in zip
            LOG.warn("No valid entry in zip:" + file.toUri());
            return;
        }
        ByteArrayOutputStream baos;
        long size = currZipEntry.getSize();
        if (size == -1) {
            baos = new ByteArrayOutputStream();
        } else {
            baos = new ByteArrayOutputStream((int) size);
        }
        int nb;
        while ((nb = zipIn.read(buf, 0, buf.length)) != -1) {
            baos.write(buf, 0, nb);
        }
        try {
            start = 0;
            end = baos.size();
            xmlSR = f.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding);
        } catch (XMLStreamException e) {
            LOG.error(e.getMessage(), e);
        }

    } else if (codecString.equalsIgnoreCase(CompressionCodec.GZIP.toString())) {
        zipIn = new GZIPInputStream(fileIn);
        codec = CompressionCodec.GZIP;
        try {
            start = 0;
            end = inSplit.getLength();
            xmlSR = f.createXMLStreamReader(zipIn, encoding);
        } catch (XMLStreamException e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        throw new UnsupportedOperationException("Unsupported codec: " + codec.name());
    }
    if (useAutomaticId) {
        idGen = new IdGenerator(file.toUri().getPath() + "-" + ((FileSplit) inSplit).getStart());
    }
}

From source file:com.espringtran.compressor4j.processor.GzipProcessor.java

/**
 * Read from compressed file/*from  www .  j ava  2s  .  c om*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    GzipCompressorInputStream cis = new GzipCompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * Opens an {@link InputStream} to the file. If it appears to be compressed, because its file name ends in
 * ".gz" or ".zip" or ".deflate", then it will be decompressed accordingly
 *
 * @param file file, possibly compressed, to open
 * @return {@link InputStream} on uncompressed contents
 * @throws IOException if the stream can't be opened or is invalid or can't be read
 *//*from  w ww  . j a  va 2 s. co  m*/
public static InputStream openMaybeDecompressing(File file) throws IOException {
    String name = file.getName();
    InputStream in = new FileInputStream(file);
    if (name.endsWith(".gz")) {
        return new GZIPInputStream(in);
    }
    if (name.endsWith(".zip")) {
        return new ZipInputStream(in);
    }
    if (name.endsWith(".deflate")) {
        return new InflaterInputStream(in);
    }
    if (name.endsWith(".bz2") || name.endsWith(".bzip2")) {
        return new BZip2CompressorInputStream(in);
    }
    return in;
}

From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java

public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties props = message.getMessageProperties();
    if (isAuthorized(props) && props.getContentType().equals("application/zip")) {
        BatchMessage msg = new BatchMessage();
        msg.setId(new String(props.getCorrelationId()));
        String timeout = "2";
        if (props.getHeaders().containsKey("timeout")) {
            timeout = props.getHeaders().get("timeout").toString();
        }//from  w ww  . j  a  v  a 2 s.co  m
        msg.setTimeout(Integer.parseInt(timeout));

        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(message.getBody()));
        ZipEntry zentry;
        try {
            while (null != (zentry = zin.getNextEntry())) {
                byte[] buff = new byte[4096];
                StringWriter json = new StringWriter();
                for (int bytesRead = 0; bytesRead > -1; bytesRead = zin.read(buff)) {
                    json.write(new String(buff, 0, bytesRead));
                }
                msg.getMessages().put(zentry.getName(), json.toString());
            }
        } catch (IOException e) {
            throw new MessageConversionException(e.getMessage(), e);
        }

        return msg;
    } else {
        throw new MessageConversionException("Invalid security key.");
    }
}

From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Read from compressed file/*from   w  w  w . ja v a2 s. co  m*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    BZip2CompressorInputStream cis = new BZip2CompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}