Example usage for java.util.zip ZipFile size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of entries in the ZIP file.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zipFile = new ZipFile(new File("testfile.zip"), ZipFile.OPEN_READ);

    System.out.println(zipFile.size());
}

From source file:com.frostwire.util.ZipUtils.java

private static int getItemCount(File file) throws IOException {
    ZipFile zip = null;
    int count = 0;
    try {//ww w  .j  a v a2s .co m
        zip = new ZipFile(file);
        count = zip.size();
    } finally {
        try {
            zip.close();
        } catch (Throwable e) {
            // ignore
        }
    }
    return count;
}

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;//from ww w .  jav  a  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:rv.comm.rcssserver.TarBz2ZipUtil.java

public static Reader getZipStream(File file) {
    try {/*from  w w w  . j  a v  a2  s  . com*/
        ZipFile zipFile = new ZipFile(file);
        if (zipFile.size() != 1) {
            System.out.println("Only support single entry zip files");
            zipFile.close();
            return null;
        } else {
            ZipEntry zipEntry = zipFile.entries().nextElement();
            return new InputStreamReader(zipFile.getInputStream(zipEntry));
        }

    } catch (IOException e) {
        // not a zip file
        System.out.println("File has zip ending, but seems to be not zip");
        return null;
    }
}

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

/**
 * Unzips a file into the specified directory.
 *
 * @param zip          file to unzip//w w w.  ja  v a2  s  .c o  m
 * @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:org.formic.util.Extractor.java

/**
 * Extracts the specified archive to the supplied destination.
 *
 * @param archive The archive to extract.
 * @param dest The directory to extract it to.
 *///from w  ww.j a v a 2 s  .c om
public static void extractArchive(File archive, File dest, ArchiveExtractionListener listener)
        throws IOException {
    ZipFile file = null;
    try {
        file = new ZipFile(archive);

        if (listener != null) {
            listener.startExtraction(file.size());
        }

        Enumeration entries = file.entries();
        for (int ii = 0; entries.hasMoreElements(); ii++) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                // create parent directories if necessary.
                String name = dest + "/" + entry.getName();
                if (name.indexOf('/') != -1) {
                    File dir = new File(name.substring(0, name.lastIndexOf('/')));
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                }

                if (listener != null) {
                    listener.startExtractingFile(ii, entry.getName());
                }

                FileOutputStream out = new FileOutputStream(name);
                InputStream in = file.getInputStream(entry);

                IOUtils.copy(in, out);

                in.close();
                out.close();

                if (listener != null) {
                    listener.finishExtractingFile(ii, entry.getName());
                }
            }
        }
    } finally {
        try {
            file.close();
        } catch (Exception ignore) {
        }
    }

    if (listener != null) {
        listener.finishExtraction();
    }
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteDictionary.java

private static void init() {
    // Raw list of xml cities.
    List cityList = null;//w w w  .ja va2  s .c o m

    // load the city dictionary from the compressed xml file.

    // get the path of the compressed file
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    String basePath = session.getServletContext().getRealPath("/WEB-INF/resources");
    basePath += "/city.xml.zip";

    // extract the file
    ZipEntry zipEntry;
    ZipFile zipFile;
    try {
        zipFile = new ZipFile(basePath);
        zipEntry = zipFile.getEntry("city.xml");
    } catch (Exception e) {
        log.error("Error retrieving records", e);
        return;
    }

    // get the xml stream and decode it.
    if (zipFile.size() > 0 && zipEntry != null) {
        try {
            BufferedInputStream dictionaryStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
            XMLDecoder xDecoder = new XMLDecoder(dictionaryStream);
            // get the city list.
            cityList = (List) xDecoder.readObject();
            dictionaryStream.close();
            zipFile.close();
            xDecoder.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            log.error("Error getting city list, not city objects", e);
            return;
        } catch (IOException e) {
            log.error("Error getting city list", e);
            return;
        }
    }

    // Finally load the object from the xml file.
    if (cityList != null) {
        dictionary = new ArrayList(cityList.size());
        City tmpCity;
        for (int i = 0, max = cityList.size(); i < max; i++) {
            tmpCity = (City) cityList.get(i);
            if (tmpCity != null && tmpCity.getCity() != null) {
                dictionary.add(new SelectItem(tmpCity, tmpCity.getCity()));
            }
        }
        cityList.clear();
        // finally sort the list
        Collections.sort(dictionary, LABEL_COMPARATOR);
    }

}

From source file:org.openflexo.toolbox.ZipUtils.java

public static final void unzip(File zip, File outputDir, IProgress progress) throws ZipException, IOException {
    Enumeration<? extends ZipEntry> entries;
    outputDir = outputDir.getCanonicalFile();
    if (!outputDir.exists()) {
        boolean b = outputDir.mkdirs();
        if (!b) {
            throw new IllegalArgumentException("Could not create dir " + outputDir.getAbsolutePath());
        }//from w  ww . j  av  a  2  s.c o  m
    }
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException(
                outputDir.getAbsolutePath() + "is not a directory or is not writeable!");
    }
    ZipFile zipFile;
    zipFile = new ZipFile(zip);
    entries = zipFile.entries();
    if (progress != null) {
        progress.resetSecondaryProgress(zipFile.size());
    }
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (progress != null) {
            progress.setSecondaryProgress(
                    FlexoLocalization.localizedForKey("unzipping") + " " + entry.getName());
        }
        if (entry.getName().startsWith("__MACOSX")) {
            continue;
        }
        if (entry.isDirectory()) {
            // Assume directories are stored parents first then
            // children.
            // This is not robust, just for demonstration purposes.
            new File(outputDir, entry.getName().replace('\\', '/')).mkdirs();
            continue;
        }
        File outputFile = new File(outputDir, entry.getName().replace('\\', '/'));
        if (outputFile.getName().startsWith("._")) {
            // This block is made to drop MacOS crap added to zip files
            if (zipFile.getEntry(
                    entry.getName().substring(0, entry.getName().length() - outputFile.getName().length())
                            + outputFile.getName().substring(2)) != null) {
                continue;
            }
            if (new File(outputFile.getParentFile(), outputFile.getName().substring(2)).exists()) {
                continue;
            }
        }
        FileUtils.createNewFile(outputFile);
        InputStream zipStream = null;
        FileOutputStream fos = null;
        try {
            zipStream = zipFile.getInputStream(entry);
            if (zipStream == null) {
                System.err.println("Could not find input stream for entry: " + entry.getName());
                continue;
            }
            fos = new FileOutputStream(outputFile);
            copyInputStream(zipStream, new BufferedOutputStream(fos));
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Could not extract: " + outputFile.getAbsolutePath()
                    + " maybe some files contains invalid characters.");
        } finally {
            IOUtils.closeQuietly(zipStream);
            IOUtils.closeQuietly(fos);
        }
    }
    Collection<File> listFiles = org.apache.commons.io.FileUtils.listFiles(outputDir, null, true);
    for (File file : listFiles) {
        if (file.isFile() && file.getName().startsWith("._")) {
            File f = new File(file.getParentFile(), file.getName().substring(2));
            if (f.exists()) {
                file.delete();
            }
        }
    }
    zipFile.close();
}

From source file:org.atombeat.xquery.functions.util.GetZipEntries.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*from   w w w  .  ja  v  a  2s. c om*/
        String path = args[0].getStringValue();
        ZipFile zf = new ZipFile(path);
        log.debug(zf.getName());
        log.debug(zf.size());
        log.debug(zf.hashCode());
        ZipEntry e;
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ValueSequence s = new ValueSequence();
        for (int i = 0; entries.hasMoreElements(); i++) {
            log.debug(i);
            e = entries.nextElement();
            log.debug(e.getName());
            log.debug(e.getComment());
            log.debug(e.isDirectory());
            log.debug(e.getCompressedSize());
            log.debug(e.getCrc());
            log.debug(e.getMethod());
            log.debug(e.getSize());
            log.debug(e.getTime());
            if (!e.isDirectory())
                s.add(new StringValue(e.getName()));
        }
        return s;
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

From source file:org.openengsb.core.api.model.FileWrapper.java

private File unzipFile(File file, String fileName) throws IOException {
    String parentPath = file.getParentFile().getAbsolutePath();
    File result = new File(parentPath + File.separator + fileName);

    BufferedOutputStream dest = null;
    BufferedInputStream is = null;

    ZipEntry entry;//  w w  w  .ja  va2  s  . c  o  m
    ZipFile zipfile = new ZipFile(file);
    int entryCount = zipfile.size();
    @SuppressWarnings("rawtypes")
    Enumeration e = zipfile.entries();
    String elementPath = "";
    if (entryCount == 1) {
        elementPath = parentPath;
    } else {
        result.mkdir();
        elementPath = parentPath + File.separator + fileName;
    }

    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();
        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte[] data = new byte[buffer];
        FileOutputStream fos = new FileOutputStream(elementPath + File.separator + entry.getName());
        dest = new BufferedOutputStream(fos, buffer);
        while ((count = is.read(data, 0, buffer)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        is.close();
    }
    FileUtils.forceDelete(file);
    return result;
}