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.cloudfoundry.client.lib.rest.CloudControllerClientV1.java

private void doUploadApplicationZipFile(String appName, File file, UploadStatusCallback callback)
        throws IOException {
    ZipFile zipFile = new ZipFile(file);
    try {// w  ww .j  av a2  s.  com
        ApplicationArchive archive = new ZipApplicationArchive(zipFile);
        uploadApplication(appName, archive, callback);
    } finally {
        zipFile.close();
    }
}

From source file:hudson.model.DirectoryBrowserSupportTest.java

@Issue("JENKINS-19752")
@Test//from   w w  w  .j a v a 2s. com
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);

    ZipFile readzip = new ZipFile(zipfile);

    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));

    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);

    is.close();
    readzip.close();
    zipfile.delete();
}

From source file:net.solarnetwork.node.backup.test.DefaultBackupManagerTest.java

@Test
public void createBackup() throws IOException {
    List<BackupResourceProvider> providers = new ArrayList<BackupResourceProvider>();
    List<BackupResource> resources = new ArrayList<BackupResource>();
    ClassPathResource txtResource = new ClassPathResource(TEST_FILE_TXT, DefaultBackupManagerTest.class);
    resources.add(new ResourceBackupResource(txtResource, TEST_FILE_TXT));
    providers.add(new StaticBackupResourceProvider(resources, RESTORE_DIR));
    manager.setResourceProviders(providers);
    final Backup backup = manager.createBackup();
    assertNotNull(backup);/*from  w w w. j  av  a 2  s  .  c  o  m*/

    final File archiveFile = new File(service.getBackupDir(),
            String.format(FileSystemBackupService.ARCHIVE_KEY_NAME_FORMAT, backup.getKey()));
    assertTrue(archiveFile.canRead());
    ZipFile zipFile = new ZipFile(archiveFile);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        int entryCount;
        for (entryCount = 0; entries.hasMoreElements(); entryCount++) {
            ZipEntry entry = entries.nextElement();
            assertEquals("The zip entry should be prefixed by the BackupResourceProvider key",
                    DefaultBackupManagerTest.class.getName() + '/' + TEST_FILE_TXT, entry.getName());
        }
        assertEquals(1, entryCount);
        this.backup = backup;
    } finally {
        zipFile.close();
    }
}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void unzip(String zipFile, String toDir) throws ZipException, IOException {

    int BUFFER = 2048;
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);
    String newPath = toDir;/*from   ww w  .j a v  a2s. c  om*/

    File toDirectory = new File(newPath);
    if (!toDirectory.exists()) {
        toDirectory.mkdir();
    }
    Enumeration zipFileEntries = zip.entries();

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

        String currentEntry = entry.getName();
        File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry));
        //System.out.println(currentEntry);
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.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);
            BufferedOutputStream 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);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zip.close();

}

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

public boolean isJarArchive(File file) {
    boolean isArchive = true;
    ZipFile zipFile = null;

    try {//from   w w w .j  a v  a 2  s  . co m
        zipFile = new ZipFile(file);
    } catch (ZipException zipCurrupted) {
        isArchive = false;
    } catch (IOException anyIOError) {
        isArchive = false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ignored) {
            }
        }
    }

    return isArchive;
}

From source file:net.technicpack.launchercore.util.ZipUtils.java

/**
 * Unzips a file into the specified directory.
 *
 * @param zip          file to unzip/*from   ww  w  .  j av a  2  s . c  om*/
 * @param output       directory to unzip into
 * @param extractRules extractRules for this zip file. May be null indicating no rules.
 * @param listener     to update progress on - may be null for no progress indicator
 */
public static void unzipFile(File zip, File output, ExtractRules extractRules, DownloadListener listener)
        throws IOException {
    if (!zip.exists()) {
        Utils.getLogger().log(Level.SEVERE, "File to unzip does not exist: " + zip.getAbsolutePath());
        return;
    }
    if (!output.exists()) {
        output.mkdirs();
    }

    ZipFile zipFile = new ZipFile(zip);
    int size = zipFile.size() + 1;
    int progress = 1;
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = null;

            try {
                entry = entries.nextElement();
            } catch (IllegalArgumentException ex) {
                //We must catch & rethrow as a zip exception because some crappy code in the zip lib will
                //throw illegal argument exceptions for malformed zips.
                throw new ZipException("IllegalArgumentException while parsing next element.");
            }

            if ((extractRules == null || extractRules.shouldExtract(entry.getName()))
                    && !entry.getName().contains("../")) {
                File outputFile = new File(output, entry.getName());

                if (outputFile.getParentFile() != null) {
                    outputFile.getParentFile().mkdirs();
                }

                if (!entry.isDirectory()) {
                    unzipEntry(zipFile, entry, outputFile);
                }
            }

            if (listener != null) {
                float totalProgress = (float) progress / (float) size;
                listener.stateChanged("Extracting " + entry.getName() + "...", totalProgress * 100.0f);
            }
            progress++;
        }
    } finally {
        zipFile.close();
    }
}

From source file:com.l2jfree.gameserver.script.faenor.FaenorScriptEngine.java

private void loadPackages() {
    File packDirectory = new File(Config.DATAPACK_ROOT, PACKAGE_DIRECTORY);

    FileFilter fileFilter = new FileFilter() {
        @Override/*  w  w  w .  j av a2  s . c  om*/
        public boolean accept(File file) {
            return file.getName().endsWith(".zip");
        }
    };

    File[] files = packDirectory.listFiles(fileFilter);
    if (files == null)
        return;
    ZipFile zipPack;

    for (File element : files) {
        try {
            zipPack = new ZipFile(element);
        } catch (ZipException e) {
            _log.error(e.getMessage(), e);
            continue;
        } catch (IOException e) {
            _log.error(e.getMessage(), e);
            continue;
        }

        ScriptPackage module = new ScriptPackage(zipPack);

        List<ScriptDocument> scripts = module.getScriptFiles();
        for (ScriptDocument script : scripts) {
            _scripts.add(script);
        }

        try {
            zipPack.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.ichi2.libanki.Exporter.java

@Override
public void exportInto(String path) throws IOException, JSONException {
    // open a zip file
    ZipFile z = new ZipFile(path);
    // if all decks and scheduling included, full export
    JSONObject media;/*from w  w w . j  a  v  a 2s .  c  o m*/
    if (mIncludeSched && mDid == null) {
        media = exportVerbatim(z);
    } else {
        // otherwise, filter
        media = exportFiltered(z, path);
    }
    // media map
    z.writeStr("media", Utils.jsonToString(media));
    z.close();
}

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

protected List<ZipAsset> getSortedListOfAssets(String path, String[] allowedExtensions) {
    List<ZipAsset> assets = new ArrayList<ZipAsset>();
    try {/*from  www  .  j  a  va 2s .c  o  m*/
        // read assets 
        ZipFile zipFile = new ZipFile(new File(path), ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();
            if (this.fileHasAllowedExtension(lower, allowedExtensions)) {
                assets.add(new ZipAsset(name, null));
            }
        }
        zipFile.close();

        // sort assets
        Collections.sort(assets);
    } catch (Exception e) {
        // nop 
    }
    return assets;
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Open an existing Zip file for adding new entries.
 * All existing entries in the zipped file will be copied in the new one.
 * /*from   w  ww  . j a  va2  s.com*/
 * @param zipFile
 * @return
 * @throws IOException 
 * @throws ZipException 
 */
public static ZipOutputStream openExistingZipFileForExtension(File zipFile) throws IOException {
    // Rename source Zip file (Attention: the String path and name of the zipFile are preserved
    File originalFileTemp = new File(
            zipFile.getParentFile().getAbsolutePath() + "/" + String.valueOf(System.currentTimeMillis()));
    zipFile.renameTo(originalFileTemp);

    ZipFile sourceZipFile = new ZipFile(originalFileTemp);
    ZipOutputStream zipOutputStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile)));

    BufferedInputStream bufferedInputStream = null;

    try {
        // copy entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();
            zipOutputStream.putNextEntry(sourceZipFileEntry);

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

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

            zipOutputStream.closeEntry();

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        zipOutputStream.flush();
        sourceZipFile.close();
        originalFileTemp.delete();

        return zipOutputStream;
    } catch (IOException e) {
        // delete existing Zip file
        if (zipFile.exists()) {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception ex) {
                }
                zipOutputStream = null;
            }
            zipFile.delete();
        }

        // revert renaming of source Zip file
        originalFileTemp.renameTo(zipFile);
        throw e;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }
    }
}