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:org.agnitas.util.ZipUtilities.java

/**
 * Readou of a Zip file/*w w  w  . j ava2 s . c  o  m*/
 * @param zipFile
 * @return all file entries
 * @throws IOException
 */
public static Map<String, byte[]> readExistingZipFile(File zipFile) throws IOException {
    Map<String, byte[]> returnMap = new HashMap<String, byte[]>();

    ZipFile sourceZipFile = null;
    BufferedInputStream bufferedInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;

    try {
        sourceZipFile = new ZipFile(zipFile);

        // readout of all entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();

            bufferedInputStream = new BufferedInputStream(sourceZipFile.getInputStream(sourceZipFileEntry));
            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                byteArrayOutputStream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedInputStream.read(bufferArray);
            }

            returnMap.put(sourceZipFileEntry.getName(), byteArrayOutputStream.toByteArray());

            byteArrayOutputStream.close();
            byteArrayOutputStream = null;

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        sourceZipFile.close();

        return returnMap;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }

        if (byteArrayOutputStream != null) {
            try {
                byteArrayOutputStream.close();
            } catch (Exception e) {
            }
            byteArrayOutputStream = null;
        }

        if (sourceZipFile != null) {
            try {
                sourceZipFile.close();
            } catch (Exception e) {
            }
            sourceZipFile = null;
        }
    }
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {//  w  w w.j  av  a2  s . co  m
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            cache.origin = file;

            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

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

private String getOPFPath(File f) {
    String ret = null;/*  w ww  . j  a  v  a  2  s.c om*/
    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry containerEntry = zipFile.getEntry(EPUB_CONTAINER_PATH);
        if (containerEntry != null) {
            InputStream is = zipFile.getInputStream(containerEntry);
            parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
            parser.setInput(is, null);
            parser.nextTag();
            ret = parseContainer();
            is.close();
        }
        zipFile.close();
    } catch (Exception e) {
        // nop
    }
    return ret;
}

From source file:nl.ordina.bag.etl.loader.MutatiesFileLoader.java

public void execute(File mutatiesFile) throws ZipException, IOException, JAXBException {
    ZipFile zipFile = new ZipFile(mutatiesFile);
    BAGExtractLevering levering = Utils.readBagExtractLevering(zipFile, FileType.MUTATIES);
    bagExtractLeveringValidator.validate(FileType.MUTATIES, levering);
    Date dateFrom = levering.getAntwoord().getVraag().getMUTExtract().getMutatieperiode().getMutatiedatumVanaf()
            .toGregorianCalendar().getTime();
    Date dateTo = levering.getAntwoord().getVraag().getMUTExtract().getMutatieperiode().getMutatiedatumTot()
            .toGregorianCalendar().getTime();
    if (bagMutatiesDAO.existsMutatiesFile(dateFrom))
        throw new ProcessingException("Mutaties File "
                + new SimpleDateFormat(Constants.DATE_FORMAT).format(dateFrom) + " already exists!");
    logger.info("Mutaties File " + new SimpleDateFormat(Constants.DATE_FORMAT).format(dateFrom) + " found.");
    zipFile.close();

    FileInputStream stream = new FileInputStream(mutatiesFile);
    bagMutatiesDAO.insertMutatiesFile(dateFrom, dateTo, IOUtils.toByteArray(stream));
    stream.close();/*www  .  jav a 2s .  co  m*/
}

From source file:com.magnet.tools.tests.ScenarioUtils.java

/**
 * Utility method to unzip a file//w w w.j  a  v  a2s .c o m
 *
 * @param file      file to unzip
 * @param outputDir destination directory
 * @throws IOException if an io exception occurs
 */
public static void unzip(File file, File outputDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                if (!entryDestination.mkdirs()) {
                    throw new IllegalStateException("Cannot create directory " + entryDestination);
                }
                continue;
            }
            if (entryDestination.getParentFile().mkdirs()) {
                throw new IllegalStateException("Cannot create directory " + entryDestination.getParentFile());
            }
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } finally {
        if (null != zipFile) {
            try {
                zipFile.close();
            } catch (Exception e) {
                /* do nothing */
            }
        }
    }
}

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

private Map<String, File> unzipFileTo(File file, File targetBaseDir) throws IOException {
    Map<String, File> entryFilesMap = new HashMap<String, File>();
    ZipFile zipFile = new ZipFile(file);
    try {/*from  w  w w .  j  a  v a 2s .  co  m*/
        for (ZipEntry zipEntry : Collections.list(zipFile.entries())) {
            InputStream in = null;
            OutputStream out = null;
            File targetFile = null;
            try {
                in = zipFile.getInputStream(zipEntry);
                targetFile = new File(targetBaseDir, zipEntry.getName());
                out = new FileOutputStream(targetFile);
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
            entryFilesMap.put(zipEntry.getName(), targetFile);
        }
    } finally {
        zipFile.close();
    }
    return entryFilesMap;
}

From source file:ccm.pay2spawn.types.MusicType.java

@Override
public void printHelpList(File configFolder) {
    musicFolder = new File(configFolder, "music");
    if (musicFolder.mkdirs()) {
        new Thread(new Runnable() {
            @Override//w ww.jav  a  2s.c  o m
            public void run() {
                try {
                    File zip = new File(musicFolder, "music.zip");
                    FileUtils.copyURLToFile(new URL(Constants.MUSICURL), zip);
                    ZipFile zipFile = new ZipFile(zip);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(musicFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        InputStream in = zipFile.getInputStream(entry);
                        OutputStream out = new FileOutputStream(entryDestination);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                    zipFile.close();
                    zip.delete();
                } catch (IOException e) {
                    Pay2Spawn.getLogger()
                            .warn("Error downloading music file. Get from github and unpack yourself please.");
                    e.printStackTrace();
                }
            }
        }, "Pay2Spawn music download and unzip").start();
    }
}

From source file:org.geosdi.geoplatform.services.utility.PublishUtility.java

private static boolean renameZipShp(String userName, InfoPreview infoPreview, String tempUserDir)
        throws ResourceNotFoundFault {
    String tempUserZipDir = PublishUtility.createDir(tempUserDir + PublishUtility.ZIP_DIR_NAME);
    boolean result = false;
    LayerPublishAction layerPublishAction = infoPreview.getLayerPublishAction();
    String newName = userName + "_shp_" + infoPreview.getNewName();
    if (layerPublishAction != null && layerPublishAction.equals(LayerPublishAction.RENAME) && newName != null
            && !newName.equalsIgnoreCase(infoPreview.getDataStoreName())) {
        String fileName = tempUserZipDir + infoPreview.getDataStoreName() + ".zip";
        File previousFile = new File(fileName);
        ZipFile zipSrc = null;
        String renameDirPath = tempUserZipDir + "rename" + System.getProperty("file.separator");
        try {//w  w w.j ava  2 s . co  m
            PublishUtility.createDir(renameDirPath);
            logger.debug("********* ManageRename renameDirPath: " + renameDirPath);
            //Decomprime il contenuto dello zip nella cartella rename
            zipSrc = new ZipFile(previousFile);
            Enumeration<? extends ZipEntry> entries = zipSrc.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                PublishUtility.extractEntryToFile(entry, zipSrc, renameDirPath);
            }
            logger.debug("********* ManageRename element unzipped");
            //Dopo l'estrazione rinominare e creare zip
            compressFiles(tempUserZipDir, renameDirPath, newName + ".zip", infoPreview.getDataStoreName(),
                    newName);
            logger.debug("********* ManageRename after compress file");
            //Cancellare vecchio zip
            previousFile.delete();
            logger.debug("********* ManageRename after delete previous file");
            result = Boolean.TRUE;
        } catch (Exception e) {
            logger.error("ERRORE : " + e);
            throw new ResourceNotFoundFault(e.getMessage());
        } finally {
            try {
                zipSrc.close();
                //Cancella cartella rename
                PublishUtility.deleteDir(renameDirPath);
                logger.debug("********* ManageRename succesfully removed rename dir");
            } catch (IOException ex) {
            }
        }
        logger.debug("Shape Zip renamed: " + result);
        if (result) {
            infoPreview.setDataStoreName(newName);
        }
    }
    return result;
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public BackupResourceIterable getBackupResources(Backup backup) {
    final File archiveFile = new File(backupDir, String.format(ARCHIVE_KEY_NAME_FORMAT, backup.getKey()));
    if (!(archiveFile.isFile() && archiveFile.canRead())) {
        log.warn("No backup archive exists for key [{}]", backup.getKey());
        Collection<BackupResource> col = Collections.emptyList();
        return new CollectionBackupResourceIterable(col);
    }/*from  w ww. j  a v  a  2  s  .com*/
    try {
        final ZipFile zf = new ZipFile(archiveFile);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        List<BackupResource> result = new ArrayList<BackupResource>(20);
        while (entries.hasMoreElements()) {
            result.add(new ZipEntryBackupResource(zf, entries.nextElement()));
        }
        return new CollectionBackupResourceIterable(result) {

            @Override
            public void close() throws IOException {
                zf.close();
            }

        };
    } catch (IOException e) {
        log.error("Error extracting backup archive entries: {}", e.getMessage());
    }
    Collection<BackupResource> col = Collections.emptyList();
    return new CollectionBackupResourceIterable(col);
}

From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*from ww  w.j  av a2 s .c  o  m*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            if (cache != null) {
                cache.origin = file;

            }
            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}