Example usage for java.util.zip ZipFile entries

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

Introduction

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

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

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

protected Map<String, String> getFiles(ZipFile zipFile) {
    Map<String, String> result = new HashMap<String, String>();
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (isMutatieFile(entry.getName()))
            result.put(getObjectType(entry.getName()), entry.getName());
    }//from  w ww. j av a 2 s  . c om
    return result;
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void unzip(File zipFile, File dir) throws Exception {

    InputStream is = null;//from   ww  w.  j  av a  2s . c om
    OutputStream os = null;
    ZipFile zip = null;

    try {

        zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        byte[] buffer = new byte[2048];
        int currentEntry = 0;

        while (e.hasMoreElements()) {

            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            File file = new File(dir, zipEntry.getName());
            currentEntry++;

            if (zipEntry.isDirectory()) {

                if (!file.exists())
                    file.mkdirs();

                continue;

            }

            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();

            try {

                int bytesLidos = 0;

                is = zip.getInputStream(zipEntry);
                os = new FileOutputStream(file);

                if (is == null)
                    throw new ZipException("Erro ao ler a entrada do zip: " + zipEntry.getName());

                while ((bytesLidos = is.read(buffer)) > 0)
                    os.write(buffer, 0, bytesLidos);

                if (listener != null)
                    listener.unzip((100 * currentEntry) / zip.size());

            } finally {

                if (is != null)
                    try {
                        is.close();
                    } catch (Exception ex) {
                    }

                if (os != null)
                    try {
                        os.close();
                    } catch (Exception ex) {
                    }

            }
        }

    } finally {

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

    }

}

From source file:com.cloudant.sync.datastore.DatastoreSchemaTests.java

@SuppressWarnings("ResultOfMethodCallIgnored") // mkdirs result should be fine
private boolean unzipToDirectory(File zipPath, File outputDirectory) {
    try {//  w  ww.j a va 2  s  .  c o m

        ZipFile zipFile = new ZipFile(zipPath);
        try {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(outputDirectory, entry.getName());
                if (entry.isDirectory())
                    entryDestination.mkdirs();
                else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    out.close();
                }
            }
        } finally {
            zipFile.close();
        }

        return true;

    } catch (Exception ex) {
        return false;
    }
}

From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;//from  w ww. j av  a  2  s.c om
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();//from   w ww .j a  va 2s . c o m
    String outputFileName = outputFile.getAbsolutePath();

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(new ZipFileWriterSource());
    itemWriter.setup(getStepExecution(outputFileName));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

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

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);

    Format format = new Format(CBZ_FORMAT);

    try {/*  w ww.  j  a v  a  2s  . c  o  m*/
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        boolean foundMetadataFile = false;
        boolean foundCover = false;
        boolean foundPlaylist = false;
        String zeCover = null;
        String zePlaylist = null;
        List<String> assets = new ArrayList<String>();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();

            if (lower.endsWith(CBZ_DEFAULT_COVER_JPG) || lower.endsWith(CBZ_DEFAULT_COVER_PNG)) {
                p.isValid(true);
                zeCover = name;
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_PLAYLIST)) {
                zePlaylist = name;
            } else if (this.fileHasAllowedExtension(lower, CBZ_IMAGE_EXTENSIONS)) {
                p.isValid(true);
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_METADATA)) {
                p.isValid(true);
                foundMetadataFile = true;
                if (this.parseMetadataFile(zipFile, ze, format)) {
                    if (format.getMetadatum("internalPathPlaylist") != null) {
                        foundPlaylist = true;
                    }
                    if (format.getMetadatum("internalPathCover") != null) {
                        foundCover = true;
                    }
                }
            } // end if metadata
        } // end while
        zipFile.close();

        // set cover
        if (!foundCover) {
            // no cover found from metadata
            // found default?
            if (zeCover != null) {
                // use default
                format.addMetadatum("internalPathCover", zeCover);
            } else {
                // sort and use the first image found
                if (assets.size() > 0) {
                    Collections.sort(assets);
                    format.addMetadatum("internalPathCover", assets.get(0));
                }
            }
        }

        // default playlist found?
        if ((!foundPlaylist) && (zePlaylist != null)) {
            format.addMetadatum("internalPathPlaylist", zePlaylist);
        }

        // set number of assets
        format.addMetadatum("numberOfAssets", "" + assets.size());

    } catch (Exception e) {
        // invalidate publication, so it will not be added to library
        p.isValid(false);
    } // end try

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:org.jboss.tools.project.examples.ProjectExamplesActivator.java

public static boolean extractZipFile(File file, File destination, IProgressMonitor monitor) {
    ZipFile zipFile = null;
    destination.mkdirs();/*w w w .  j a  v  a  2  s .  c o m*/
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            if (monitor.isCanceled()) {
                return false;
            }
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                monitor.setTaskName("Extracting " + entry.getName());
                File dir = new File(destination, entry.getName());
                dir.mkdirs();
                continue;
            }
            monitor.setTaskName("Extracting " + entry.getName());
            File entryFile = new File(destination, entry.getName());
            entryFile.getParentFile().mkdirs();
            InputStream in = null;
            OutputStream out = null;
            try {
                in = zipFile.getInputStream(entry);
                out = new FileOutputStream(entryFile);
                copy(in, out);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }
    } catch (IOException e) {
        ProjectExamplesActivator.log(e);
        return false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return true;
}

From source file:it.readbeyond.minstrel.unzipper.Unzipper.java

private String list(String inputZip) throws IOException, JSONException {
    // list all files
    List<String> acc = new ArrayList<String>();
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
    Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
    while (zipFileEntries.hasMoreElements()) {
        acc.add(zipFileEntries.nextElement().getName());
    }/*from   w  w w  .j ava2s  .c  om*/
    zipFile.close();

    // sort
    Collections.sort(acc);

    // return JSON string
    return stringify(acc);
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testResourceZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();/*from  ww  w. ja v a  2s  .c  o  m*/
    String outputFileName = outputFile.getAbsolutePath();

    ZipFileWriterSource source = new ZipFileWriterSource();
    source.setResource(new FileSystemResource(outputFileName));

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(source);
    itemWriter.setup(getStepExecution(null));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:dpfmanager.shell.modules.client.core.ClientService.java

private boolean unzipFileIntoDirectory(File file, File dest) {
    try {/*from  w w  w.jav  a 2  s  . co m*/
        ZipFile zipFile = new ZipFile(file);
        Enumeration files = zipFile.entries();
        while (files.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            File f = new File(dest.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(f);

            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
        }
    } catch (IOException e) {
        return false;
    }
    return true;
}