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.l2jfree.gameserver.util.JarClassLoader.java

private byte[] loadClassData(String name) throws IOException {
    byte[] classData = null;
    for (String jarFile : _jars) {
        ZipFile zipFile = null;
        DataInputStream zipStream = null;

        try {//from   w w  w .  ja  v a 2 s. c o  m
            File file = new File(jarFile);
            zipFile = new ZipFile(file);
            String fileName = name.replace('.', '/') + ".class";
            ZipEntry entry = zipFile.getEntry(fileName);
            if (entry == null)
                continue;
            classData = new byte[(int) entry.getSize()];
            zipStream = new DataInputStream(zipFile.getInputStream(entry));
            zipStream.readFully(classData, 0, (int) entry.getSize());
            break;
        } catch (IOException e) {
            _log.warn(jarFile + ":", e);
            continue;
        } finally {
            try {
                if (zipFile != null)
                    zipFile.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
            try {
                if (zipStream != null)
                    zipStream.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
        }
    }
    if (classData == null)
        throw new IOException("class not found in " + _jars);
    return classData;
}

From source file:de.onyxbits.raccoon.ptools.ToolSupport.java

private void unzip(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    try {//  w w w.j  ava  2 s  .c  om
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(binDir, entry.getName());
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java

/**
 * Reads a theme from file/*from w ww .jav  a2 s . c om*/
 */
private Theme read(final File file) throws ThemeException {
    ZipFile zipFile = null;
    try {
        if (!file.exists()) {
            throw new ThemeNotFoundException(file.getName());
        }
        zipFile = new ZipFile(file);
        final Properties properties = properties(zipFile);
        final Theme theme = fromProperties(properties);
        theme.setFilename(file.getName());
        return theme;
    } catch (final Exception e) {
        throw new ThemeException(e);
    } finally {
        try {
            zipFile.close();
        } catch (final Exception e) {
            // Ignore
        }
    }
}

From source file:com.liferay.mobile.sdk.core.tests.MobileSDKCoreTests.java

private void checkJar(File jar, boolean src) throws Exception {
    assertTrue(jar.exists());/*from  ww w .j  ava  2  s . c  om*/

    final ZipFile zipFile = new ZipFile(jar);
    final ZipEntry manifest = zipFile.getEntry("META-INF/MANIFEST.MF");

    assertNotNull(manifest);

    final String manifestContents = CoreUtil.readStreamToString(zipFile.getInputStream(manifest));

    assertTrue(manifestContents.startsWith("Manifest-Version: 1.0"));

    boolean valid = false;

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

    while (entries.hasMoreElements()) {
        final String entryName = entries.nextElement().getName();

        if (entryName.startsWith(PACKAGE.split("\\.")[0]) && entryName.endsWith(src ? ".java" : ".class")) {
            valid = true;
            break;
        }
    }

    zipFile.close();

    assertTrue(valid);
}

From source file:Main.java

public static void unzip(String strZipFile) {

    try {/*w w  w .  j av  a  2  s.  co  m*/
        /*
         * STEP 1 : Create directory with the name of the zip file
         * 
         * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries
         */
        File fSourceZip = new File(strZipFile);
        String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
        File temp = new File(zipPath);
        temp.mkdir();
        System.out.println(zipPath + " created");

        /*
         * STEP 2 : Extract entries while creating required sub-directories
         */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());

            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();

            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                // System.out.println("Extracting " + destinationFilePath);

                /*
                 * Get the InputStream for current entry of the zip file using
                 * 
                 * InputStream getInputStream(Entry entry) method.
                 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

                int b;
                byte buffer[] = new byte[1024];

                /*
                 * read the current entry from the zip file, extract it and write the extracted file.
                 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }

                // flush the output stream and close it.
                bos.flush();
                bos.close();

                // close the input stream.
                bis.close();
            }

        }
        zipFile.close();
    } catch (IOException ioe) {
        System.out.println("IOError :" + ioe);
    }

}

From source file:org.cloudfoundry.client.lib.UploadApplicationPayloadTest.java

@Test
public void shouldPackOnlyMissingResources() throws Exception {
    ZipFile zipFile = new ZipFile(SampleProjects.springTravel());
    try {/*from   w  w  w .ja v  a2  s. c  o  m*/
        ApplicationArchive archive = new ZipApplicationArchive(zipFile);
        CloudResources allResources = new CloudResources(archive);
        List<CloudResource> resources = new ArrayList<CloudResource>(allResources.asList());
        resources.remove(0);
        CloudResources knownRemoteResources = new CloudResources(resources);
        UploadApplicationPayload payload = new UploadApplicationPayload(archive, knownRemoteResources);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileCopyUtils.copy(payload.getInputStream(), bos);
        assertThat(payload.getArchive(), is(archive));
        assertThat(payload.getTotalUncompressedSize(), is(93));
        assertThat(bos.toByteArray().length, is(2451));
    } finally {
        zipFile.close();
    }
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipPublish.java

private Boolean writeArchive(final File dest, final String path) {
    final boolean isJar = isJarOperation();
    FileOutputStream fos = null;/*from  www.  j  a v a 2  s . c  om*/
    ZipOutputStream zos = null;
    ZipFile zf = null;
    try {
        fos = new FileOutputStream(dest);
        zos = isJar ? new JarOutputStream(fos) : new ZipOutputStream(fos);

        zf = isJar ? new JarFile(dest) : new ZipFile(dest);

        final ZipEntry entry = zf.getEntry(path);
        zos.putNextEntry(entry);
        copy(stream, zos);

        return true;
    } catch (final IOException e) {
        error = new TransferException("Failed to write path: %s to NEW archive: %s. Reason: %s", e, path, dest,
                e.getMessage());
    } finally {
        closeQuietly(zos);
        closeQuietly(fos);
        if (zf != null) {
            //noinspection EmptyCatchBlock
            try {
                zf.close();
            } catch (final IOException e) {
            }
        }
        closeQuietly(stream);
    }

    return false;
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extract(File compressedFile, String export) throws IOException {
    log.trace("Compressed file {}", compressedFile);

    File file = null;/*from   ww  w. ja  v  a2s .  co  m*/
    if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) {
        file = unBZip2(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("tar.gz")) {
        file = unTarGz(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("gz")) {
        file = unGzip(compressedFile);
    } else {
        ZipFile zipFolder = new ZipFile(compressedFile);
        Enumeration<?> enu = zipFolder.entries();

        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();
            long size = zipEntry.getSize();
            long compressedSize = zipEntry.getCompressedSize();
            log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize);

            file = new File(compressedFile.getParentFile() + File.separator + name);
            if (!file.exists() || WdmConfig.getBoolean("wdm.override")) {
                if (name.endsWith("/")) {
                    file.mkdirs();
                    continue;
                }

                File parent = file.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                InputStream is = zipFolder.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();
                file.setExecutable(true);
            } else {
                log.debug(file + " already exists");
            }

        }
        zipFolder.close();
    }

    file = checkPhantom(compressedFile, export);

    log.trace("Resulting binary file {}", file.getAbsoluteFile());
    return file.getAbsoluteFile();
}

From source file:org.geoserver.rest.util.IOUtils.java

/**
 * Inflate the provided {@link ZipFile} in the provided output directory.
 * //  w  w  w  .  ja  v  a 2s.  co m
 * @param archive the {@link ZipFile} to inflate.
 * @param outputDirectory the directory where to inflate the archive.
 * @throws IOException in case something bad happens.
 * @throws FileNotFoundException in case something bad happens.
 */
public static void inflate(ZipFile archive, File outputDirectory, String fileName)
        throws IOException, FileNotFoundException {

    final Enumeration<? extends ZipEntry> entries = archive.entries();
    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (!entry.isDirectory()) {
                final String name = entry.getName();
                final String ext = FilenameUtils.getExtension(name);
                final InputStream in = new BufferedInputStream(archive.getInputStream(entry));
                final File outFile = new File(outputDirectory,
                        fileName != null ? new StringBuilder(fileName).append(".").append(ext).toString()
                                : name);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));

                IOUtils.copyStream(in, out, true, true);

            } else {
                //if the entry is a directory attempt to make it
                new File(outputDirectory, entry.getName()).mkdirs();
            }
        }
    } finally {
        try {
            archive.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.isLoggable(Level.FINE);
        }
    }

}

From source file:org.openmrs.module.clinicalsummary.rule.EvaluableSummaryRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 *//*  www  . ja va 2  s.  c o m*/
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering clinical summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(CLINICAL_SUMMARY_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, CLINICAL_SUMMARY_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        EvaluableRuleVisitor visitor = new EvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}