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:net.technicpack.utilslib.ZipUtils.java

public static void unzipFile(File zip, File output, IZipFileFilter fileFilter, DownloadListener listener)
        throws IOException, InterruptedException {
    if (!zip.exists()) {
        Utils.getLogger().log(Level.SEVERE, "File to unzip does not exist: " + zip.getAbsolutePath());
        return;/*  w w w  . j  a  va  2 s  .c o  m*/
    }
    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()) {
            if (Thread.interrupted())
                throw new InterruptedException();

            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 (!entry.getName().contains("../")
                    && (fileFilter == null || fileFilter.shouldExtract(entry.getName()))) {
                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.sshtools.j2ssh.util.DynamicClassLoader.java

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

    try {//from  w w  w  . j a  v a2  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:nl.ordina.bag.etl.loader.ExtractLoader.java

public void execute(File extractFile) throws ZipException, IOException, ParseException, JAXBException {
    ZipFile zipFile = new ZipFile(extractFile);
    BAGExtractLevering levering = Utils.readBagExtractLevering(zipFile, FileType.EXTRACT);
    bagExtractLeveringValidator.validate(FileType.EXTRACT, levering);
    processBAGExtractFile(levering, zipFile);

    Date date = new SimpleDateFormat(Constants.BAG_DATE_FORMAT)
            .parse(levering.getAntwoord().getVraag().getLVCExtract().getStandTechnischeDatum());
    long id = bagMutatiesDAO.insertMutatiesFile(new Date(0), date, new byte[] {});
    bagMutatiesDAO.setMutatiesFileStatus(id, ProcessingStatus.PROCESSED);

    zipFile.close();
}

From source file:hudson.model.DirectoryBrowserSupportSEC904Test.java

private List<String> getListOfEntriesInDownloadedZip(UnexpectedPage zipPage) throws Exception {
    List<String> result;

    File zipfile = null;//  ww  w.  j a v  a 2 s .  c o m
    ZipFile readzip = null;
    try {
        zipfile = download(zipPage);

        readzip = new ZipFile(zipfile);
        result = readzip.stream().map(ZipEntry::getName).collect(Collectors.toList());
    } finally {
        if (readzip != null) {
            readzip.close();
        }
        if (zipfile != null) {
            zipfile.delete();
        }
    }
    return result;
}

From source file:org.pentaho.platform.web.servlet.UploadFileUtils.java

/**
 * Gets the uncompressed file size of a .zip file.
 * //w  w  w.j ava  2  s .  c  o  m
 * @param theFile
 * @return long uncompressed file size.
 * @throws IOException
 *           mbatchelor
 */
private long getUncompressedZipFileSize(File theFile) throws IOException {
    long rtn = 0;
    ZipFile zf = new ZipFile(theFile);
    try {
        Enumeration<? extends ZipEntry> zfEntries = zf.entries();
        ZipEntry ze = null;
        while (zfEntries.hasMoreElements()) {
            ze = zfEntries.nextElement();
            rtn += ze.getSize();
        }
    } finally {
        try {
            zf.close();
        } catch (Exception ignored) {
            //ignored
        }
    }
    return rtn;
}

From source file:com.mc.printer.model.utils.ZipHelper.java

/**
 * jar????/*w w w.j a  v  a2 s . c  o  m*/
 *
 * @param jar ????jar
 * @param subDir jar???????
 * @param loc ????
 * @param force ????
 * @return
 */
public static boolean unZip(String jar, String subDir, String loc, boolean force) {
    try {
        File base = new File(loc);
        if (!base.exists()) {
            base.mkdirs();
        }

        ZipFile zip = new ZipFile(new File(jar));
        Enumeration<? extends ZipEntry> entrys = zip.entries();
        while (entrys.hasMoreElements()) {
            ZipEntry entry = entrys.nextElement();
            String name = entry.getName();
            if (!name.startsWith(subDir)) {
                continue;
            }
            //subDir
            name = name.replace(subDir, "").trim();
            if (name.length() < 2) {
                log.debug(name + "  < 2");
                continue;
            }
            if (entry.isDirectory()) {
                File dir = new File(base, name);
                if (!dir.exists()) {
                    dir.mkdirs();
                    log.debug("create directory");
                } else {
                    log.debug("the directory is existing.");
                }
                log.debug(name + " is a directory");
            } else {
                File file = new File(base, name);
                if (file.exists() && force) {
                    file.delete();
                }
                if (!file.exists()) {
                    InputStream in = zip.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(in, file);
                    log.debug("create file.");
                    in.close();
                } else {
                    log.debug("the file is existing");
                }
                log.debug(name + " is not a directory");
            }
        }
        zip.close();
    } catch (ZipException ex) {
        ex.printStackTrace();
        log.error("file unzip failed.", ex);
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        log.error("file IO failed", ex);
        return false;
    }
    return true;
}

From source file:com.github.promeg.configchecker.Main.java

/**
 * Tries to open an input file as a Zip archive (jar/apk) with a
 * "classes.dex" inside.//from  w w w .j  ava 2s .  c  om
 */
void openInputFileAsZip(String fileName, List<String> dexFiles) throws IOException {
    ZipFile zipFile;

    // Try it as a zip file.
    try {
        zipFile = new ZipFile(fileName);
    } catch (FileNotFoundException fnfe) {
        // not found, no point in retrying as non-zip.
        System.err.println("Unable to open '" + fileName + "': " + fnfe.getMessage());
        throw fnfe;
    } catch (ZipException ze) {
        // not a zip
        return;
    }

    // Open and add all files matching "classes.*\.dex" in the zip file.
    for (ZipEntry entry : Collections.list(zipFile.entries())) {
        if (entry.getName().matches("classes.*\\.dex")) {
            dexFiles.add(openDexFile(zipFile, entry).getAbsolutePath());
        }
    }

    zipFile.close();
}

From source file:org.paxle.core.doc.impl.BasicDocumentFactoryTest.java

public void testStoreMarshalledCommand() throws IOException, ParseException {
    // Create the ZIP file
    final File outFile = File.createTempFile("command", ".zip");
    outFile.deleteOnExit();/*from  w  ww  .ja v a 2 s  .  c  om*/
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outFile));

    // creating a test command
    final ICommand cmd = this.createTestCommand();

    // marshal command
    final ZipEntry commandEntry = new ZipEntry("command.xml");
    commandEntry.setComment("command.xml");
    zipOut.putNextEntry(commandEntry);

    final TeeOutputStream out = new TeeOutputStream(System.out, zipOut);
    final Map<String, DataHandler> attachments = this.docFactory.marshal(cmd, out);
    zipOut.closeEntry();

    // write attachments
    if (attachments != null) {
        for (Entry<String, DataHandler> attachment : attachments.entrySet()) {
            final String cid = attachment.getKey();
            final DataHandler data = attachment.getValue();

            final ZipEntry zipEntry = new ZipEntry(cid);
            zipEntry.setComment(data.getName());
            zipOut.putNextEntry(zipEntry);

            IOUtils.copy(data.getInputStream(), zipOut);
            zipOut.closeEntry();
        }
    }
    zipOut.close();
    System.out.println("Command written into file: " + outFile.toString());

    // print content
    final ZipFile zf = new ZipFile(outFile);
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();
        System.out.println(entry.getName() + ": " + entry.getComment());
    }
    zf.close();
}

From source file:org.overlord.commons.osgi.vfs.VfsBundle.java

/**
 * Indexes the JAR file by getting a SHA1 hash of its MANIFEST.MF file.
 * @param entryFile/*  w  w w.  j  a  va2  s . com*/
 */
private void indexJar(File entryFile) {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(entryFile);
        ZipEntry zipEntry = zipFile.getEntry("META-INF/MANIFEST.MF"); //$NON-NLS-1$
        if (zipEntry != null) {
            InputStream inputStream = zipFile.getInputStream(zipEntry);
            String hash = DigestUtils.shaHex(inputStream);
            index.put(hash, entryFile);
        }
    } catch (Exception e) {
        // Do nothing - invalid JAR file?
    } finally {
        try {
            if (zipFile != null)
                zipFile.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * @param options specific options to use when loading the properties
 * @throws IOException if there is a problem accessing the properties
 *//* w  ww .  ja  v  a 2 s.  com*/
private void loadProperties(final DAVOptions options) throws IOException {
    final boolean zipExists = new File(zipFilename).exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists));
    }

    properties.clear();

    // check to see if a zip file exists - if it doesn't we assume it's an old binary format
    if (zipModel && zipExists) {
        LOG.info("Reading model from filename: " + zipFilename);

        final ZipFile zipFile = new ZipFile(zipFilename);
        try {
            final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename));
            // load properties
            properties.clear();
            properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options));
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) { // NOPMD
                // ignore since there is not much we can do anyway
            }
        }
    } else {
        final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString());
        if (propertyFile.exists() && propertyFile.canRead()) {
            LOG.debug("Loading properties from " + propertyFile.getAbsolutePath());
            properties.addAll(loadProperties(FileUtils.openInputStream(propertyFile), options));
        }
    }
}