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:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

private void explode(ZipFile file, File dir) throws IOException {
    for (Enumeration<? extends ZipEntry> en = file.entries(); en.hasMoreElements();) {
        ZipEntry entry = en.nextElement();
        File next = new File(dir, entry.getName());
        if (entry.isDirectory()) {
            next.mkdirs();//from ww w .  j  av  a  2 s .  co  m
        } else {
            next.createNewFile();
            if (next.getParentFile() != null) {
                next.getParentFile().mkdirs();
            }
            InputStream in = file.getInputStream(entry);
            OutputStream out = new FileOutputStream(next);
            try {
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:com.isomorphic.maven.packaging.Distribution.java

/**
 * Extract the relevant contents from each file in the distribution.  Additionally creates ZIP/JAR
 * files from specified resources (e.g., javadoc).
 * //from ww  w  . ja  v a  2 s . c  o  m
 * @param to The directory to which each file should be extracted.
 * @throws IOException
 */
public void unpack(File to) throws IOException {

    outer: for (File file : files) {

        String ext = FilenameUtils.getExtension(file.getName()).toUpperCase();

        //copy uncompressed files to target, renaming as necessary per 'contents' configuration
        if (!"ZIP".equals(ext)) {
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(file.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey()));
                    FileUtils.copyFile(file, target);
                    LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath());
                    continue outer;
                }
            }
            FileUtils.copyFileToDirectory(file, new File(to, "lib"));
            continue outer;
        }

        //otherwise extract contents (again renaming / relocating contents as necessary)
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(entry.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey()));
                    FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target);
                    LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath());
                }
            }
        }
        zip.close();
    }

    /*
     * Create any number of assemblies by dropping their resources here.
     * Each subdirectory will get zipped up and then deleted
     */
    File assembliesDir = new File(to, "assembly");

    @SuppressWarnings("unchecked")
    Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File arg0) {
            return arg0.isDirectory();
        }
    }));
    for (File assembly : assemblies) {
        String name = FilenameUtils.getBaseName(assembly.getName());
        LOGGER.debug("Copying resources for assembly '{}'", name);
        ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip"));
        FileUtils.deleteQuietly(assembly);
    }

    LOGGER.debug("Repackaging Javadoc...");
    File docLib = new File(to, "doc/lib");

    //TODO these paths should probably all be stuck in some constant
    File client = FileUtils.getFile(to, "doc/api/client");
    if (client.exists()) {
        ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar"));
    }

    File server = FileUtils.getFile(to, "doc/api/server");
    if (server.exists()) {
        ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar"));
    }
}

From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java

public Model getArchetypePom(File jar) throws XmlPullParserException, UnknownArchetype, IOException {
    ZipFile zipFile = null;
    try {//w ww  . j a  v a 2s  .  c o m
        String pomFileName = null;
        zipFile = getArchetypeZipFile(jar);

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry el = (ZipEntry) enumeration.nextElement();

            String entry = el.getName();
            if (entry.startsWith("META-INF") && entry.endsWith("pom.xml")) {
                pomFileName = entry;
            }
        }

        if (pomFileName == null) {
            return null;
        }

        ZipEntry pom = zipFile.getEntry(pomFileName);

        if (pom == null) {
            return null;
        }
        return pomManager.readPom(zipFile.getInputStream(pom));
    } finally {
        closeZipFile(zipFile);
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void extractArchiveFile(File file, String destinationPath)
        throws ZipException, FileNotFoundException, IOException {
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    File entryDestination = null;
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        entryDestination = new File(destinationPath, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            entryDestination.mkdirs();//  w  ww.  j av  a2s  .co m
        } else {
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:com.google.appinventor.buildserver.util.AARLibrary.java

/**
 * Unpacks the Android Archive to a directory in the file system. The unpacking operation will
 * create a new directory named with the archive's package name to prevent collisions with
 * other Android Archives.//from   w  w w . j  av a 2 s.  co  m
 * @param path the path to where the archive will be unpacked.
 * @throws IOException if any error occurs attempting to read the archive or write new files to
 *                     the file system.
 */
public void unpackToDirectory(final File path) throws IOException {
    ZipFile zip = null;
    try {
        zip = new ZipFile(aarPath);
        packageName = extractPackageName(zip);
        basedir = new File(path, packageName);
        if (!basedir.mkdirs()) {
            throw new IOException("Unable to create directory for AAR package");
        }
        InputStream input = null;
        OutputStream output = null;
        Enumeration<? extends ZipEntry> i = zip.entries();
        while (i.hasMoreElements()) {
            ZipEntry entry = i.nextElement();
            File target = new File(basedir, entry.getName());
            if (entry.isDirectory() && !target.exists() && !target.mkdirs()) {
                throw new IOException("Unable to create directory " + path.getAbsolutePath());
            } else if (!entry.isDirectory()) {
                try {
                    output = new FileOutputStream(target);
                    input = zip.getInputStream(entry);
                    IOUtils.copy(input, output);
                } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
                catalog(target);
            }
        }
        resdir = new File(basedir, "res");
        if (!resdir.exists()) {
            resdir = null;
        }
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:org.zilverline.service.CollectionManagerImpl.java

/**
 * unZips a given zip file into cache directory with derived name. e.g. c:\temp\file.zip wil be unziiped into
 * [cacheDir]\file_zip\./*from w  w w  .  ja  v  a2  s  .  c  om*/
 * 
 * @param sourceZipFile the ZIP file to be unzipped
 * @param thisCollection the collection whose cache and contenDir is used
 * 
 * @return File (new) directory containing zip file
 */
public static File unZip(final File sourceZipFile, final FileSystemCollection thisCollection) {
    // specify buffer size for extraction
    final int aBUFFER = 2048;
    File unzipDestinationDirectory = null;
    ZipFile zipFile = null;
    FileOutputStream fos = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;

    try {
        // Specify destination where file will be unzipped
        unzipDestinationDirectory = file2CacheDir(sourceZipFile, thisCollection);
        log.info("unzipping " + sourceZipFile + " into " + unzipDestinationDirectory);
        // Open Zip file for reading
        zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
        // Create an enumeration of the entries in the zip file
        Enumeration zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            log.debug("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()) {
                bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[aBUFFER];
                // write the current file to disk
                fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, aBUFFER);
                // read and write until last byte is encountered
                while ((currentByte = bis.read(data, 0, aBUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                bis.close();
            }
        }
        zipFile.close();
        // delete the zip file if it is in the cache, we don't need to store
        // it, since we've extracted the contents
        if (FileUtils.isIn(sourceZipFile, thisCollection.getCacheDirWithManagerDefaults())) {
            sourceZipFile.delete();
        }
    } catch (Exception e) {
        log.error("Can't unzip: " + sourceZipFile, e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (dest != null) {
                dest.close();
            }
            if (bis != null) {
                bis.close();
            }
        } catch (IOException e1) {
            log.error("Error closing files", e1);
        }
    }

    return unzipDestinationDirectory;
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void unzip(final File zipFile, final File destDir) throws MojoExecutionException {

    try {/*from  w  ww . j  ava2  s  .com*/
        final ZipFile zip = new ZipFile(zipFile);
        try {
            final Enumeration<? extends ZipEntry> enu = zip.entries();
            while (enu.hasMoreElements()) {
                final ZipEntry entry = (ZipEntry) enu.nextElement();
                final File file = new File(entry.getName());
                if (file.isAbsolute()) {
                    throw new IllegalArgumentException(
                            "Only relative path entries are allowed! [" + entry.getName() + "]");
                }
                if (entry.isDirectory()) {
                    final File dir = new File(destDir, entry.getName());
                    createIfNecessary(dir);
                } else {
                    final File outFile = new File(destDir, entry.getName());
                    createIfNecessary(outFile.getParentFile());
                    final InputStream in = new BufferedInputStream(zip.getInputStream(entry));
                    try {
                        final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
                        try {
                            final byte[] buf = new byte[4096];
                            int len;
                            while ((len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        } finally {
                            out.close();
                        }
                    } finally {
                        in.close();
                    }
                }
            }
        } finally {
            zip.close();
        }

    } catch (final IOException ex) {
        throw new MojoExecutionException("Error unzipping event store archive: " + zipFile, ex);
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIPZIPdescFileName//w w  w .j  av  a  2  s.  co  m
 * 
 * @param zipFileName ?ZIP
 * @param descFileName 
 */
public static boolean unZipFiles(String zipFileName, String descFileName) {
    String descFileNames = descFileName;
    if (!descFileNames.endsWith(File.separator)) {
        descFileNames = descFileNames + File.separator;
    }
    try {
        // ?ZIPZipFile
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipEntry entry = null;
        String entryName = null;
        String descFileDir = null;
        byte[] buf = new byte[4096];
        int readByte = 0;
        // ?ZIPentry
        @SuppressWarnings("rawtypes")
        Enumeration enums = zipFile.entries();
        // ??entry
        while (enums.hasMoreElements()) {
            entry = (ZipEntry) enums.nextElement();
            // entry??
            entryName = entry.getName();
            descFileDir = descFileNames + entryName;
            if (entry.isDirectory()) {
                // entry
                new File(descFileDir).mkdirs();
                continue;
            } else {
                // entry
                new File(descFileDir).getParentFile().mkdirs();
            }
            File file = new File(descFileDir);
            // ?
            OutputStream os = new FileOutputStream(file);
            // ZipFileentry?
            InputStream is = zipFile.getInputStream(entry);
            while ((readByte = is.read(buf)) != -1) {
                os.write(buf, 0, readByte);
            }
            os.close();
            is.close();
        }
        zipFile.close();
        log.debug("?!");
        return true;
    } catch (Exception e) {
        log.debug("" + e.getMessage());
        return false;
    }
}

From source file:org.digidoc4j.impl.BDocContainer.java

private String getBdocMimeTypeFromZip(String path) {
    logger.debug("Get mime type from zip for " + path);
    String mimeType;//from  w  w  w.  j  a v  a2  s  . c o  m
    try {
        ZipFile zipFile = new ZipFile(path);
        ZipEntry entry = zipFile.getEntry("mimetype");
        if (entry == null) {
            logger.error("Unsupported format, mimetype missing");
            throw new UnsupportedFormatException("Not an asic-e document. Mimetype is missing.");
        }
        InputStream stream = zipFile.getInputStream(entry);
        mimeType = IOUtils.toString(stream);
        stream.close();
        zipFile.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new DigiDoc4JException(e);
    }

    logger.debug("Mime type " + mimeType);
    return mimeType;
}