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:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile//from w ww  . ja va 2s.  co  m
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).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, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            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
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                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();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.geowe.server.upload.FileUploadZipServlet.java

private String readZipFile(ZipFile zipFile) {
    String content = EMPTY;//from  w  ww .  j a va  2  s  . c o  m

    try {

        Enumeration<?> enu = zipFile.entries();
        if (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            if (zipEntry.isDirectory()) {
                content = BAD_FORMAT;
            } else if (!(zipEntry.getName().equals(PRJ_FILE_NAME))) {
                content = BAD_FORMAT;
            } else {
                InputStream is = zipFile.getInputStream(zipEntry);
                content = new java.util.Scanner(is).useDelimiter("\\A").next();
            }

            // String name = zipEntry.getName();
            // long size = zipEntry.getSize();
            // long compressedSize = zipEntry.getCompressedSize();
            // LOG.info("name: " + name + " | size: " + size
            // + " | compressed size: " + compressedSize);

        }
        zipFile.close();

    } catch (IOException e) {
        LOG.error("Se produce error en ZipFile: " + e.getMessage());
        e.printStackTrace();
    }

    return content;
}

From source file:net.sourceforge.dita4publishers.tools.DitaDxpHelperTest.java

public void xtestZipMapBos() throws Exception {
    MapBosProcessorOptions options = new DitaDxpOptions();
    File outputZipFile = File.createTempFile("textZipMapBos", ".dxp");
    DitaDxpHelper.zipMapBos(mapBos, outputZipFile, options);
    assertTrue("DXP file doesn't exist", outputZipFile.exists());
    ZipFile zipFile = new ZipFile(outputZipFile);
    List<ZipEntry> entries = new ArrayList<ZipEntry>();

    Enumeration<? extends ZipEntry> enumer = zipFile.entries();
    while (enumer.hasMoreElements()) {
        entries.add(enumer.nextElement());
    }//  w ww . ja  v  a  2  s  . c  om

    assertEquals(11, entries.size());

    // Put more checks here.

    outputZipFile.deleteOnExit();
}

From source file:UnpackedJarFile.java

public static void unzipToDirectory(ZipFile zipFile, File destDir) throws IOException {
    Enumeration entries = zipFile.entries();
    try {// www .j  a  v a  2 s. co m
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                File dir = new File(destDir, entry.getName());
                createDirectory(dir);
            } else {
                File file = new File(destDir, entry.getName());
                createDirectory(file.getParentFile());
                OutputStream out = null;
                InputStream in = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    in = zipFile.getInputStream(entry);
                    writeAll(in, out);
                } finally {
                    if (null != out) {
                        out.close();
                    }
                    if (null != in) {
                        in.close();
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:com.streamsets.datacollector.bundles.TestSupportBundleManager.java

private ZipFile zipFile(List<String> bundles, BundleType bundleType) throws Exception {
    InputStream bundleStream = manager.generateNewBundle(bundles, bundleType).getInputStream();
    File outputFile = File.createTempFile("test-support-bundle", ".zip");
    outputFile.deleteOnExit();// ww w. ja  v a 2 s  . com

    try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
        IOUtils.copy(bundleStream, outputStream);
    }

    ZipFile zipFile = new ZipFile(outputFile);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    LOG.debug("Archive content:");
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        LOG.debug("Entry {}", entry.getName());
    }

    return zipFile;
}

From source file:org.gradle.api.internal.changedetection.state.DefaultClasspathEntryHasher.java

private HashCode hashJar(FileDetails fileDetails, Hasher hasher,
        ClasspathContentHasher classpathContentHasher) {
    ZipFile zipFile = null;
    try {/*from  w  w  w .j  a v a2  s.c om*/
        zipFile = new ZipFile(new File(fileDetails.getPath()));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        // Ensure we visit the zip entries in a deterministic order
        Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (!zipEntry.isDirectory()) {
                entriesByName.put(zipEntry.getName(), zipEntry);
            }
        }
        for (ZipEntry zipEntry : entriesByName.values()) {
            visit(zipFile, zipEntry, hasher, classpathContentHasher);
        }
        return hasher.hash();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
}

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 ww w .  j  a  v  a  2 s  .  co  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:org.gradle.api.internal.changedetection.state.JvmClassHasher.java

public HashCode hashJarFile(FileDetails fileDetails) {
    HashCode signature = persistentCache.get(fileDetails.getContent().getContentMd5());
    if (signature != null) {
        return signature;
    }/*from ww  w .ja va 2  s . co  m*/

    File file = new File(fileDetails.getPath());
    final Hasher hasher = createHasher();
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        // Ensure we visit the zip entries in a deterministic order
        Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".class")) {
                entriesByName.put(zipEntry.getName(), zipEntry);
            }
        }
        for (ZipEntry zipEntry : entriesByName.values()) {
            visit(zipFile, zipEntry, hasher);
        }
    } catch (Exception e) {
        throw new UncheckedIOException("Could not calculate the signature for Jar file " + file, e);
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
    signature = hasher.hash();
    persistentCache.put(fileDetails.getContent().getContentMd5(), signature);
    return signature;
}

From source file:ClassFinder.java

/**
 * <P>Iterates through the files in a zip looking for files that may be
 * classes. This is not recursive as zip's in zip's are not searched by the
 * classloader either.</p>//from  ww  w. j a  v a2s.  c o m
 *
 * @param file The ZipFile to be searched
 */
protected void processZip(ZipFile file) {
    Enumeration files = file.entries();

    while (files.hasMoreElements()) {
        Object tfile = files.nextElement();
        ZipEntry child = (ZipEntry) tfile;
        if (child.getName().endsWith(".class")) {
            addClassName(getClassName(child.getName()));

            this.foundClasses++;
        }
    }
}

From source file:com.alibaba.otter.shared.common.utils.extension.classpath.FileSystemClassScanner.java

private Class<?> scanInJar(String jarFileName, String className) {
    ZipFile zipfile = null;

    try {//from   ww  w. j av a  2 s. c om
        zipfile = new ZipFile(jarFileName);
        Enumeration<?> zipenum = zipfile.entries();
        ZipEntry entry = null;
        String tempClassName = null;

        while (zipenum.hasMoreElements()) {
            entry = (ZipEntry) zipenum.nextElement();
            tempClassName = entry.getName();

            if (tempClassName.endsWith(".class")) {
                tempClassName = StringUtils.replace(FilenameUtils.removeExtension(tempClassName), "/", ".");
                if (tempClassName.equals(className)) {
                    try {
                        return fileClassLoader.loadClass(className);
                    } catch (Exception ex) {
                        logger.warn("WARN ## load this class has an error,the fileName is = " + className, ex);
                    }
                }
            }
        }
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        }
    }
    return null;
}