Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *///w w w  .  j  a v  a2 s .  c o  m
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(this.updateFolder, name);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException e) {
        this.plugin.getLogger().log(Level.SEVERE,
                "The auto-updater tried to unzip a new update file, but was unsuccessful.", e);
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}

From source file:com.taobao.android.builder.tools.sign.LocalSignHelper.java

private static Predicate<String> getNoCompressPredicate(File inputFile) throws IOException {
    List<String> paths = new ArrayList<>();
    ZipFile zFile = new ZipFile(inputFile);
    Enumeration<? extends ZipEntry> enumeration = zFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = enumeration.nextElement();
        if (zipEntry.getMethod() == 0) {
            paths.add(zipEntry.getName());
        }/*  www  .j ava  2 s .co  m*/
    }
    return s -> paths.contains(s);

}

From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java

/**
 * Calculates the SHA256 Hash of a class in a file.
 * //from   w w  w .ja  v  a 2s .c  o m
 * @param file the archive contains the class
 * @param resourcePath the name of the class
 * @return the MD% Hash as Hex-Value
 * @throws IOException if any error occurs on reading class in archive
 */
private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException {
    class Sha256CacheKey {
        final File file;
        final String resourcePath;

        Sha256CacheKey(File file, String resourcePath) {
            this.file = file;
            this.resourcePath = resourcePath;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;

            Sha256CacheKey key = (Sha256CacheKey) o;

            return file.equals(key.file) && resourcePath.equals(key.resourcePath);
        }

        public int hashCode() {
            return 31 * file.hashCode() + resourcePath.hashCode();
        }
    }

    final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath);
    if (CACHED_SHA256.containsKey(key)) {
        return (String) CACHED_SHA256.get(key);
    }

    ZipFile zip = new ZipFile(file);
    ZipEntry zipEntry = zip.getEntry(resourcePath);
    if (zipEntry == null) {
        throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file);
    }

    String sha256;

    InputStream in = zip.getInputStream(zipEntry);
    try {
        sha256 = DigestUtils.sha256Hex(in);
    } finally {
        IOUtils.closeQuietly(in);
    }

    CACHED_SHA256.put(key, sha256);

    return sha256;
}

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

private void computeDuplicateFiles(File jar) throws IOException {
    ZipFile file = new ZipFile(jar);
    Enumeration<? extends ZipEntry> list = file.entries();
    while (list.hasMoreElements()) {
        ZipEntry ze = list.nextElement();
        if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) { // Exclude META-INF and Directories
            List<File> l = jars.get(ze.getName());
            if (l == null) {
                l = new ArrayList<File>();
                jars.put(ze.getName(), l);
            }/*from  w w w. j av a2 s  .  c  om*/
            l.add(jar);
        }
    }
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * unzip a file in the same directory as the zipped file
 * //  w  w  w. j  av  a2 s.  co m
 * @param file
 *            The file to unzip
 */
public static void unzipFile(File file) {
    logger.info("will Extracting file: " + file.getName());
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile;

    try {
        zipFile = new ZipFile(file);

        entries = zipFile.entries();

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

            if (entry.isDirectory()) {
                // Assume directories are stored parents first then
                // children.
                (new File(entry.getName())).mkdir();
                continue;
            }

            logger.info("Extracting file: " + entry.getName() + " to " + file.getParent() + File.separator
                    + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(file.getParent() + File.separator + entry.getName())));
        }

        zipFile.close();
    } catch (IOException e) {
        logger.error("can not unzip " + file.getName() + " : " + e.getMessage(), e);
        throw new ImporterException(e);
    }
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void installSkin(File skinDir, File file) throws SkinException, IOException {
    ZipFile myZipFile = null;/*from  w w  w .j  av  a2 s.  co m*/
    try {
        myZipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> myEntries = myZipFile.entries();
        while (myEntries.hasMoreElements()) {
            ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement();
            handleEntry(myZipEntry, myZipFile, skinDir);
        }
    } catch (ZipException z) {
        throw new SkinException("Error reading zip file", z);
    } finally {
        if (myZipFile != null) {
            try {
                myZipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }

    }
}

From source file:com.ikon.util.DocConverter.java

/**
 * Convert ZIP to PDF/*from  w w w. java  2 s . c  om*/
 */
@SuppressWarnings("rawtypes")
public void zip2pdf(File input, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from ZIP to PDF **");
    FileOutputStream fos = null;
    ZipFile zipFile = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        zipFile = new ZipFile(input);
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            doc.add(new Paragraph(12F, entry.getName()));
        }

        doc.close();
        zipFile.close();
    } catch (ZipException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

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

private void computeDuplicateFiles(File jar) throws IOException {
    ZipFile file = new ZipFile(jar);
    Enumeration<? extends ZipEntry> list = file.entries();
    while (list.hasMoreElements()) {
        ZipEntry ze = list.nextElement();
        if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) { // Exclude
            // META-INF
            // and
            // Directories
            List<File> l = m_jars.get(ze.getName());
            if (l == null) {
                l = new ArrayList<File>();
                m_jars.put(ze.getName(), l);
            }/*from www  .j  a  va 2s .com*/
            l.add(jar);
        }
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Calculate the md5sum on all files in the map pack file (except those in META-INF) and their filenames inclusive
 * path in the map pack file).//from   w w w . ja va  2 s.  c o  m
 * 
 * @param mapPackFile
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        MessageDigest md5Total = MessageDigest.getInstance("MD5");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory())
                continue;
            // Do not hash files from META-INF
            String name = entry.getName();
            if (name.toUpperCase().startsWith("META-INF"))
                continue;
            md5.reset();
            InputStream in = zip.getInputStream(entry);
            byte[] data = Utilities.getInputBytes(in);
            in.close();
            // name = name.replaceAll("\\\\", "/");
            byte[] digest = md5.digest(data);
            log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\"");
            md5Total.update(digest);
            md5Total.update(name.getBytes());
        }
        String md5sum = Hex.encodeHexString(md5Total.digest());
        log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum);
        return md5sum;
    } finally {
        zip.close();
    }
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@SuppressWarnings("rawtypes")
@Override//from w w w.  j a v a 2 s  . c  om
public String uploadMappings(MultipartFile mapping) {
    String msg = "";
    String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
            + File.separator;
    String mappingFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER
            + File.separator;
    String mappingName = mapping.getOriginalFilename();

    if (mappingName.endsWith(".zip")) {
        boolean allFailed = true;
        File tempMappings = new File(tempFolderName + mappingName);

        (new File(tempFolderName)).mkdirs();
        try {
            mapping.transferTo(tempMappings);

            try {
                ZipFile zipfile = new ZipFile(tempMappings);

                for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) e.nextElement();

                    if (entry.isDirectory()) {
                        System.out.println("Incorrect file (Can't be a folder instead): " + entry.getName()
                                + " has been ignored");
                    } else if (entry.getName().endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
                        File outputFile = new File(mappingFolderName, entry.getName());

                        if (outputFile.exists()) {
                            System.out.println(
                                    "File: " + outputFile.getName() + " already exists and has been ignored");
                        } else {
                            BufferedInputStream inputStream = new BufferedInputStream(
                                    zipfile.getInputStream(entry));
                            BufferedOutputStream outputStream = new BufferedOutputStream(
                                    new FileOutputStream(outputFile));

                            try {
                                System.out.println("Extracting: " + entry);
                                IOUtils.copy(inputStream, outputStream);
                                allFailed = false;
                            } finally {
                                outputStream.close();
                                inputStream.close();
                            }
                        }
                    } else {
                        System.out.println("Incorrect file: " + entry.getName() + " has been ignored");
                    }
                }
                if (!allFailed) {
                    msg = Context.getMessageSourceService()
                            .getMessage("dhisconnector.uploadMapping.groupSuccess");
                } else {
                    msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.allFailed");
                }
                FileUtils.deleteDirectory(new File(tempFolderName));
            } catch (Exception e) {
                System.out.println("Error while extracting file:" + mapping.getName() + " ; " + e);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (mappingName.endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
        try {
            File uploadedMapping = new File(mappingFolderName + mappingName);
            if (uploadedMapping.exists()) {
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.exists");
            } else {
                mapping.transferTo(uploadedMapping);
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.singleSuccess");
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.wrongType");
    }

    return msg;
}