Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory.//from   w w  w  .j av a 2s  . com
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

From source file:be.fedict.eid.pkira.blm.model.contracts.CertificateTest.java

protected void validateNextZipEntry(ZipFile zipFile, String fileName, String expectedText) throws IOException {
    ZipEntry entry = zipFile.getEntry(fileName);

    byte[] expectedBytes = expectedText.getBytes();
    byte[] actualBytes = new byte[expectedBytes.length];
    zipFile.getInputStream(entry).read(actualBytes);

    assertEquals(entry.getName(), fileName);
    assertEquals(entry.getSize(), expectedBytes.length);
    assertEquals(actualBytes, expectedBytes);
}

From source file:org.eclipse.mylyn.commons.sdk.util.CommonTestUtil.java

private static void unzip(ZipFile zipFile, File rootDstDir, File dstDir, int depth) throws IOException {

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    try {/*from w w w  . j a  v a  2  s. c  o m*/
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String entryName = entry.getName();
            File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
            file.getParentFile().mkdirs();
            InputStream src = null;
            OutputStream dst = null;
            try {
                src = zipFile.getInputStream(entry);
                dst = new FileOutputStream(file);
                transferData(src, dst);
            } finally {
                if (dst != null) {
                    try {
                        dst.close();
                    } catch (IOException e) {
                        // don't need to catch this
                    }
                }
                if (src != null) {
                    try {
                        src.close();
                    } catch (IOException e) {
                        // don't need to catch this
                    }
                }
            }
        }
    } finally {
        try {
            zipFile.close();
        } catch (IOException e) {
            // don't need to catch this
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * copy project log files from the exported project
 * @param zip the ZIP file./*from  ww  w.j av a2s. c  o m*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectLog(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(LOG_DIR)) {
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), aRepository.getProjectLogFile(aProject));
            LOG.info(
                    "Imported log for project [" + aProject.getName() + "] with id [" + aProject.getId() + "]");
        }
    }
}

From source file:org.jboss.pvt.harness.validators.JBossSignatureCheckValidator.java

@Override
public boolean validate(PVTConfiguration pvtConfiguration) throws PVTException {
    File eapDir = pvtConfiguration.getDistributionDirectory();

    Collection<File> jarFiles = DirUtils.listFilesRecursively(eapDir, new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isFile() && pathname.getName().endsWith(".jar");
        }/*from w  w w .j  a  v a2 s .c  om*/
    });

    logger.info("Jars: " + Arrays.toString(jarFiles.toArray()));

    boolean signed = mustSigned(pvtConfiguration);
    try {
        for (File jarFile : jarFiles) {
            if (jarFile.isFile()) {
                if (shouldExclude(jarFile, pvtConfiguration)) {
                    logger.warn("Skip Jar, " + jarFile);
                    continue;
                }
                ZipFile zipFile = new ZipFile(jarFile);
                StringWriter sw = new StringWriter();
                IOUtils.copy(
                        new InputStreamReader(zipFile.getInputStream(zipFile.getEntry("META-INF/MANIFEST.MF"))),
                        sw);
                signed = sw.getBuffer().toString().contains("Digest:");

                if (signed != mustSigned(pvtConfiguration)) {
                    logger.debug("Found " + (mustSigned(pvtConfiguration) ? "unsigned" : "signed") + " jar: "
                            + jarFile);
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new PVTSystemException(e);
    }

    return (signed == mustSigned(pvtConfiguration));
}

From source file:org.gradle.api.internal.changedetection.state.DefaultClasspathEntryHasher.java

private void visit(ZipFile zipFile, ZipEntry zipEntry, Hasher hasher,
        ClasspathContentHasher classpathContentHasher) throws IOException {
    InputStream inputStream = null;
    try {/*www .ja va  2s  .  c om*/
        inputStream = zipFile.getInputStream(zipEntry);
        byte[] src = ByteStreams.toByteArray(inputStream);
        classpathContentHasher.updateHash(zipFile, zipEntry, hasher, src);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.WebJars.java

public static void extract(final AbstractVertxMojo mojo, File in, File out, boolean stripVersion)
        throws IOException {
    ZipFile file = new ZipFile(in);
    try {/*from   w w w .j  a  v a2  s  .  c  o m*/
        Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith(WEBJAR_LOCATION) && !entry.isDirectory()) {
                // Compute destination.
                File output = new File(out, entry.getName().substring(WEBJAR_LOCATION.length()));
                if (stripVersion) {
                    String path = entry.getName().substring(WEBJAR_LOCATION.length());
                    Matcher matcher = WEBJAR_INTERNAL_PATH_REGEX.matcher(path);
                    if (matcher.matches()) {
                        output = new File(out, matcher.group(1) + "/" + matcher.group(3));
                    } else {
                        mojo.getLog().warn(path
                                + " does not match the regex - did not strip the version for this" + " file");
                    }
                }
                InputStream stream = null;
                try {
                    stream = file.getInputStream(entry);
                    output.getParentFile().mkdirs();
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, output);
                } catch (IOException e) {
                    mojo.getLog().error("Cannot unpack " + entry.getName() + " from " + file.getName(), e);
                    throw e;
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given apk into the given destination directory
 * /* ww w  . jav  a  2s  .com*/
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws IOException
 */
public static void extractApk(File archive, File dest) throws IOException {

    @SuppressWarnings("resource") // Closing it later results in an error
    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;

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

        String entryFileName = entry.getName();

        byte[] buffer = new byte[16384];
        int len;

        File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {
            if (entry.getSize() == 0) {
                LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName()
                        + ". Looks corrupted.");
                continue;
            }

            try {
                bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,...

                bis = new BufferedInputStream(zipFile.getInputStream(entry));

                while ((len = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            } catch (IOException ioe) {
                LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for "
                        + archive.getName() + " may not be accurate");
            } finally {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
                // if (zipFile != null) zipFile.close();
            }
        }

    }

}

From source file:org.apache.sysml.validation.ValidateLicAndNotice.java

/**
 * This will return the file from zip file and store it in specified location.
 *
 * @param   zipFileName is the name of zip file from which file to be extracted.
 * @param   fileName is the name of the file to be extracted.
 * @param   strDestLoc is the location where file will be extracted.
 * @param    bFirstDirLevel to indicate to get file from first directory level.
 * @return  Sucess or Failure/*from w w w  .j a  v a 2 s.  com*/
 */
public static boolean extractFileFromZip(String zipFileName, String fileName, String strDestLoc,
        boolean bFirstDirLevel) {
    boolean bRetCode = Constants.bFAILURE;
    try {
        BufferedOutputStream bufOut = null;
        BufferedInputStream bufIn = null;
        ZipEntry entry;
        ZipFile zipfile = new ZipFile(zipFileName);
        Enumeration e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = (ZipEntry) e.nextElement();
            if (!entry.getName().endsWith(fileName))
                continue;
            //Get file at root (in single directory) level. This is for License in root location.
            if (bFirstDirLevel && (entry.getName().indexOf('/') != entry.getName().lastIndexOf('/')))
                continue;
            bufIn = new BufferedInputStream(zipfile.getInputStream(entry));
            int count;
            byte data[] = new byte[Constants.BUFFER];
            String strOutFileName = strDestLoc == null ? entry.getName() : strDestLoc + "/" + fileName;
            FileOutputStream fos = new FileOutputStream(strOutFileName);
            bufOut = new BufferedOutputStream(fos, Constants.BUFFER);
            while ((count = bufIn.read(data, 0, Constants.BUFFER)) != -1) {
                bufOut.write(data, 0, count);
            }
            bufOut.flush();
            bufOut.close();
            bufIn.close();
            bRetCode = Constants.bSUCCESS;
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bRetCode;
}

From source file:org.eurocarbdb.action.admin.LoadTaxonomy.java

/********************************* 
                               */*  w ww .  ja va 2  s  .  co  m*/
                               *   Open zip file from local file, extract names & nodes files from the 
                               *   zip stream, assign to local fields for later parsing.
                               */
protected void initDefaultInputStreams() throws IOException {
    log.debug("initialising default input streams for NCBI names/nodes files");
    String ncbi_zipfile_name = Eurocarb.getProperty("ncbi.taxonomy.localfile");
    ZipFile ncbi_zipfile = new ZipFile(ncbi_zipfile_name);

    ZipEntry names_file = ncbi_zipfile.getEntry("names.dmp");
    ZipEntry nodes_file = ncbi_zipfile.getEntry("nodes.dmp");

    this.instreamNames = ncbi_zipfile.getInputStream(names_file);
    this.instreamNodes = ncbi_zipfile.getInputStream(nodes_file);
}