Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly)
        throws IOException {
    ZipFile zin = new ZipFile(jarFile);

    for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) {
        ZipEntry ze = en.nextElement();

        if (ze.isDirectory()) {
            continue;
        }/*from ww  w . j av a 2s.  co  m*/

        String zn = ze.getName();

        if (metaInfOnly) {
            if (!zn.startsWith("META-INF/")) {
                continue;
            }

            if (this.extractDuplicates && !entries.add(zn)) {
                continue;
            }

            if (!this.apkMetaInf.isIncluded(zn)) {
                continue;
            }
        }
        final ZipEntry ne;
        if (ze.getMethod() == ZipEntry.STORED) {
            ne = new ZipEntry(ze);
        } else {
            ne = new ZipEntry(zn);
        }

        zos.putNextEntry(ne);

        InputStream is = zin.getInputStream(ze);

        copyStreamWithoutClosing(is, zos);

        is.close();
        zos.closeEntry();
    }

    zin.close();
}

From source file:org.zeroturnaround.zip.ZipsTest.java

private void assertContainsEntryWithSeparatorrs(File zip, String entryPath, String expectedSeparator)
        throws IOException {
    char expectedSeparatorChar = expectedSeparator.charAt(0);
    String osSpecificEntryPath = entryPath.replace('\\', expectedSeparatorChar).replace('/',
            expectedSeparatorChar);//from w  ww.  j  a va 2s.co  m
    ZipFile zf = new ZipFile(zip);
    try {
        if (zf.getEntry(osSpecificEntryPath) == null) {
            char unexpectedSeparatorChar = expectedSeparatorChar == '/' ? '\\' : '/';
            String nonOsSpecificEntryPath = entryPath.replace('\\', unexpectedSeparatorChar).replace('/',
                    unexpectedSeparatorChar);
            if (zf.getEntry(nonOsSpecificEntryPath) != null) {
                fail(zip.getAbsolutePath() + " is not packed using directory separator '"
                        + expectedSeparatorChar + "', found entry '" + nonOsSpecificEntryPath + "', but not '"
                        + osSpecificEntryPath + "'"); // used to fail with this message on windows
            }
            StringBuilder sb = new StringBuilder();
            Enumeration entries = zf.entries();
            while (entries.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) entries.nextElement();
                sb.append(ze.getName()).append(",");
            }
            fail(zip.getAbsolutePath() + " doesn't contain entry '" + entryPath
                    + "', but found following entries: " + sb.toString());
        }
    } finally {
        zf.close();
    }
    assertTrue("Didn't find entry '" + entryPath + "' from " + zip.getAbsolutePath(),
            ZipUtil.containsEntry(zip, entryPath));
}

From source file:org.onehippo.repository.xml.ExportImportPackageTest.java

@Test
public void testExportImportPackage() throws Exception {
    HippoSession session = (HippoSession) this.session;
    final File file = session.exportEnhancedSystemViewPackage("/test", true);
    ZipFile zipFile = new ZipFile(file);
    InputStream esvIn = null;/*from   ww w.jav a  2s  .  c o  m*/
    try {
        List<? extends ZipEntry> entries = Collections.list(zipFile.entries());
        assertEquals(2, entries.size()); // esv.xml and one binary
        ZipEntry esvXmlEntry = null;
        ZipEntry binaryEntry = null;
        for (ZipEntry entry : entries) {
            if (entry.getName().equals("esv.xml")) {
                esvXmlEntry = entry;
            } else {
                binaryEntry = entry;
            }
        }
        assertNotNull(esvXmlEntry);
        assertNotNull(binaryEntry);
        InputStream binaryInput = zipFile.getInputStream(binaryEntry);
        assertEquals("test", IOUtils.toString(binaryInput));
        binaryInput.close();

        if (log.isDebugEnabled()) {
            log.debug("Created package at " + file.getPath());
        }
        ContentResourceLoader contentResourceLoader = new ZipFileContentResourceLoader(zipFile);
        esvIn = contentResourceLoader.getResourceAsStream("esv.xml");
        session.importEnhancedSystemViewXML("/test", esvIn, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW,
                ImportReferenceBehavior.IMPORT_REFERENCE_NOT_FOUND_THROW, contentResourceLoader);
        assertTrue(session.nodeExists("/test/test"));
        final Node test = session.getNode("/test/test");
        assertTrue(test.hasProperty("test"));
        binaryInput = test.getProperty("test").getBinary().getStream();
        assertEquals("test", IOUtils.toString(binaryInput));
        binaryInput.close();
    } finally {
        IOUtils.closeQuietly(esvIn);
        zipFile.close();
        if (!log.isDebugEnabled()) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:org.jvnet.hudson.plugins.thinbackup.backup.BackupSet.java

/**
 * Unzips this backup set into a directory within the specified directory if it was initialized from a ZIP file. Does
 * NOT change <i>this</i>. deleteUnzipDir() may be called if the unzipped BackupSet is no longer needed. The directory
 * the BackupSet was unzipped to can be retrieved with getUnzipDir(). Before using the returned BackupSet, it should
 * be checked if it is valid.//from  w  w  w .  ja  v  a 2 s  . c  o m
 * 
 * @param directory target directory
 * @return a new BackupSet referencing the unzipped directories, or the current BackupSet if it was either not created
 *         from a ZIP file or is invalid. In case of an error an invalid BackupSet is returned.
 * @throws IOException - if an I/O error occurs.
 */
public BackupSet unzipTo(final File directory) throws IOException {
    BackupSet result = null;

    if (inZipFile && isValid()) {
        if (!directory.exists()) {
            directory.mkdirs();
        }
        unzipDir = new File(directory, getBackupSetZipFileName().replace(HudsonBackup.ZIP_FILE_EXTENSION, ""));
        if (!unzipDir.exists()) {
            unzipDir.mkdirs();
        }

        final ZipFile zipFile = new ZipFile(backupSetzipFile);
        final byte data[] = new byte[DirectoriesZipper.BUFFER_SIZE];
        final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            final ZipEntry entry = zipEntries.nextElement();

            final String fullPathToEntry = entry.getName();
            final String pathToEntry = fullPathToEntry.substring(0,
                    fullPathToEntry.lastIndexOf(File.separator));
            final File entryDir = new File(unzipDir, pathToEntry);
            entryDir.mkdirs();
            final String entryName = fullPathToEntry.substring(fullPathToEntry.lastIndexOf(File.separator) + 1);

            final BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));

            final FileOutputStream fos = new FileOutputStream(
                    new File(unzipDir + File.separator + pathToEntry, entryName));
            final BufferedOutputStream dest = new BufferedOutputStream(fos, DirectoriesZipper.BUFFER_SIZE);

            int count = 0;
            while ((count = is.read(data)) != -1) {
                dest.write(data, 0, count);
            }

            dest.flush();
            dest.close();
        }
        zipFile.close();

        final File[] backups = unzipDir.listFiles();
        if (backups.length > 0) {
            result = new BackupSet(backups[0]);
        } else {
            // in case of an error (i.e. nothing was unzipped) return an invalid BackupSet
            result = new BackupSet(unzipDir);
        }
    } else {
        result = this;
    }

    return result;
}

From source file:org.b3log.symphony.processor.CaptchaProcessor.java

/**
 * Loads captcha.//  ww  w. j  ava 2  s  .  co  m
 */
private synchronized void loadCaptchas() {
    LOGGER.trace("Loading captchas....");

    try {
        captchas = new Image[CAPTCHA_COUNT];

        ZipFile zipFile;

        if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) {
            final InputStream inputStream = SymphonyServletListener.class.getClassLoader()
                    .getResourceAsStream("captcha_static.zip");
            final File file = File.createTempFile("b3log_captcha_static", null);
            final OutputStream outputStream = new FileOutputStream(file);

            IOUtils.copy(inputStream, outputStream);
            zipFile = new ZipFile(file);

            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        } else {
            final URL captchaURL = SymphonyServletListener.class.getClassLoader()
                    .getResource("captcha_static.zip");

            zipFile = new ZipFile(captchaURL.getFile());
        }

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

        int i = 0;

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

            final BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    zipFile.getInputStream(entry));
            final byte[] captchaCharData = new byte[bufferedInputStream.available()];

            bufferedInputStream.read(captchaCharData);
            bufferedInputStream.close();

            final Image image = IMAGE_SERVICE.makeImage(captchaCharData);

            image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.')));

            captchas[i] = image;

            i++;
        }

        zipFile.close();
    } catch (final Exception e) {
        LOGGER.error("Can not load captchs!");

        throw new IllegalStateException(e);
    }

    LOGGER.trace("Loaded captch images");
}

From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java

private byte[] extractBar(File barFile) {
    ZipFile zipFile = null;
    InputStream entryInputStream = null;
    byte[] processBytes = null;
    try {/*from  ww w .j  av a  2s .  c  om*/
        zipFile = new ZipFile(barFile);

        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                if (entry.getName().endsWith(".proc")) { //$NON-NLS-1$
                    entryInputStream = zipFile.getInputStream(entry);
                    processBytes = IOUtils.toByteArray(entryInputStream);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (entryInputStream != null) {
            try {
                entryInputStream.close();
            } catch (IOException e) {
            }
        }
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }

    }
    return processBytes;
}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }// www  . ja va 2 s  .c  o m

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:org.rioproject.impl.util.DownloadManager.java

/**
 * Extract an archive/*  ww w .j a  va  2  s  .co m*/
 *
 * @param directory the directory to extract to
 * @param archive The archive to extract
 *
 * @return An ExtractResults class detailing what was extracted
 *
 * @throws IOException if there are errors extracting the archive
 */
@SuppressWarnings("PMD.AvoidReassigningParameters")
public static ExtractResults extract(File directory, File archive) throws IOException {

    String extractedToPath = null;
    int extractSize = 0;
    ZipFile zipFile = null;
    List<File> extractList = new ArrayList<File>();
    if (archive.getName().endsWith(".gz") || archive.getName().endsWith(".gzip")) {
        archive = dealWithGZIP(archive);
    }
    if (archive.getName().endsWith("tar")) {
        unTar(archive, directory);
        return (new ExtractResults(extractedToPath, extractSize, extractList));
    }
    try {
        zipFile = new ZipFile(archive);
        Enumeration zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
            if (zipEntry.isDirectory()) {
                File file = makeChildFile(directory, zipEntry.getName());
                if (file.mkdirs()) {
                    logger.trace("Created {}", file.getPath());
                }
                if (extractedToPath == null) {
                    extractedToPath = getExtractedToPath(file, directory);
                }
            } else {
                File file = makeChildFile(directory, zipEntry.getName());
                //System.out.println("Writing : "+file.getCanonicalPath());
                extractList.add(file);
                String fullPath = FileUtils.getFilePath(file);
                int index = fullPath.lastIndexOf(File.separatorChar);
                String installPath = fullPath.substring(0, index);
                File targetPath = new File(installPath);
                if (!targetPath.exists()) {
                    if (targetPath.mkdirs()) {
                        logger.trace("Created {}", file.getPath());
                    }
                    if (!targetPath.exists())
                        throw new IOException("Failed to create : " + installPath);
                }
                if (!targetPath.canWrite())
                    throw new IOException("Can not write to : " + installPath);
                InputStream in = zipFile.getInputStream(zipEntry);
                extractSize += writeFileFromInputStream(in, file, archive.length(), false);
            }
        }
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
    return (new ExtractResults(extractedToPath, extractSize, extractList));
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerCBZ.java

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);

    Format format = new Format(CBZ_FORMAT);

    try {//from  w w w .j ava  2s .c  o m
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        boolean foundMetadataFile = false;
        boolean foundCover = false;
        boolean foundPlaylist = false;
        String zeCover = null;
        String zePlaylist = null;
        List<String> assets = new ArrayList<String>();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();

            if (lower.endsWith(CBZ_DEFAULT_COVER_JPG) || lower.endsWith(CBZ_DEFAULT_COVER_PNG)) {
                p.isValid(true);
                zeCover = name;
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_PLAYLIST)) {
                zePlaylist = name;
            } else if (this.fileHasAllowedExtension(lower, CBZ_IMAGE_EXTENSIONS)) {
                p.isValid(true);
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_METADATA)) {
                p.isValid(true);
                foundMetadataFile = true;
                if (this.parseMetadataFile(zipFile, ze, format)) {
                    if (format.getMetadatum("internalPathPlaylist") != null) {
                        foundPlaylist = true;
                    }
                    if (format.getMetadatum("internalPathCover") != null) {
                        foundCover = true;
                    }
                }
            } // end if metadata
        } // end while
        zipFile.close();

        // set cover
        if (!foundCover) {
            // no cover found from metadata
            // found default?
            if (zeCover != null) {
                // use default
                format.addMetadatum("internalPathCover", zeCover);
            } else {
                // sort and use the first image found
                if (assets.size() > 0) {
                    Collections.sort(assets);
                    format.addMetadatum("internalPathCover", assets.get(0));
                }
            }
        }

        // default playlist found?
        if ((!foundPlaylist) && (zePlaylist != null)) {
            format.addMetadatum("internalPathPlaylist", zePlaylist);
        }

        // set number of assets
        format.addMetadatum("numberOfAssets", "" + assets.size());

    } catch (Exception e) {
        // invalidate publication, so it will not be added to library
        p.isValid(false);
    } // end try

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

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 . j a v  a 2s .  com*/
 * 
 * @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;
}