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:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

public static void unzipFile(File zipArchive, File outputDirectory) {
    ZipFile zipfile = null;
    try {// ww w . j  a v a2  s  .  co  m
        zipfile = new ZipFile(zipArchive);
    } catch (IOException ex) {
        throw new OpenShiftToolsException("Exception occured while processing zip file.\n" + ex.getMessage());
    }
    Enumeration<? extends ZipEntry> entries = zipfile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        unzipEntry(zipfile, entry, outputDirectory);
    }
}

From source file:org.jahia.utils.zip.ZipEntryCharsetDetector.java

private static boolean canRead(File file, Charset charset) throws IOException {
    boolean canRead = true;
    ZipFile zip = null;
    try {//w ww  .  j  a v  a2s.c  om
        zip = charset != null ? new ZipFile(file, charset) : new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        try {
            while (entries.hasMoreElements()) {
                entries.nextElement();
            }
        } catch (IllegalArgumentException e) {
            canRead = false;
        }
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return canRead;
}

From source file:ClassFinder.java

private static void findClassesInPathsDir(String strPathElement, File dir, Set<String> listClasses)
        throws IOException {
    String[] list = dir.list();/*from ww  w. j  av a 2s  . co  m*/
    for (int i = 0; i < list.length; i++) {
        File file = new File(dir, list[i]);
        if (file.isDirectory()) {
            // Recursive call
            findClassesInPathsDir(strPathElement, file, listClasses);
        } else if (list[i].endsWith(DOT_CLASS) && file.exists() && (file.length() != 0)) {
            final String path = file.getPath();
            listClasses.add(path.substring(strPathElement.length() + 1, path.lastIndexOf(".")) // $NON-NLS-1$
                    .replace(File.separator.charAt(0), '.')); // $NON-NLS-1$
        } else if (list[i].endsWith(DOT_JAR) && file.exists() && (file.length() != 0)) {
            ZipFile zipFile = new ZipFile(file);
            Enumeration entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                String strEntry = entries.nextElement().toString();
                if (strEntry.endsWith(DOT_CLASS)) {
                    listClasses.add(fixClassName(strEntry));
                }
            }
            zipFile.close();
        }
    }
}

From source file:com.termmed.utils.ResourceUtils.java

/**
 * Gets the resources from jar file./* w  w  w  .  j av  a 2s.co  m*/
 *
 * @param file the file
 * @param pattern the pattern
 * @return the resources from jar file
 */
private static Collection<String> getResourcesFromJarFile(final File file, final Pattern pattern) {
    final ArrayList<String> retval = new ArrayList<String>();
    ZipFile zf;
    try {
        zf = new ZipFile(file);
    } catch (final ZipException e) {
        throw new Error(e);
    } catch (final IOException e) {
        throw new Error(e);
    }
    final Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        final ZipEntry ze = (ZipEntry) e.nextElement();
        final String fileName = ze.getName();
        final boolean accept = pattern.matcher(fileName).matches();
        if (accept) {
            retval.add(fileName);
        }
    }
    try {
        zf.close();
    } catch (final IOException e1) {
        throw new Error(e1);
    }
    return retval;
}

From source file:dk.netarkivet.common.utils.ZipUtils.java

/** Unzip a zipFile into a directory.  This will create subdirectories
 * as needed.//from  w  w w  .j  a  v a2s  .  co m
 *
 * @param zipFile The file to unzip
 * @param toDir The directory to create the files under.  This directory
 * will be created if necessary.  Files in it will be overwritten if the
 * filenames match.
 */
public static void unzip(File zipFile, File toDir) {
    ArgumentNotValid.checkNotNull(zipFile, "File zipFile");
    ArgumentNotValid.checkNotNull(toDir, "File toDir");
    ArgumentNotValid.checkTrue(toDir.getAbsoluteFile().getParentFile().canWrite(),
            "can't write to '" + toDir + "'");
    ArgumentNotValid.checkTrue(zipFile.canRead(), "can't read '" + zipFile + "'");
    InputStream inputStream = null;
    ZipFile unzipper = null;
    try {
        try {
            unzipper = new ZipFile(zipFile);
            Enumeration<? extends ZipEntry> entries = unzipper.entries();
            while (entries.hasMoreElements()) {
                ZipEntry ze = entries.nextElement();
                File target = new File(toDir, ze.getName());
                // Ensure that its dir exists
                FileUtils.createDir(target.getCanonicalFile().getParentFile());
                if (ze.isDirectory()) {
                    target.mkdir();
                } else {
                    inputStream = unzipper.getInputStream(ze);
                    FileUtils.writeStreamToFile(inputStream, target);
                    inputStream.close();
                }
            }
        } finally {
            if (unzipper != null) {
                unzipper.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Failed to unzip '" + zipFile + "'", e);
    }
}

From source file:org.jdal.util.ZipFileUtils.java

/**
 * Unzip file to dirname/*w  w  w  . ja va 2 s .c om*/
 * 
 * @param file file to unzip
 * @param dirname dir name to store unzipped entries
 */
public static void unzip(ZipFile file, String dirname) {
    File dir = new File(dirname);
    dir.mkdirs();

    List<ZipEntry> dirs = new ArrayList<ZipEntry>();
    List<ZipEntry> files = new ArrayList<ZipEntry>();

    Enumeration<? extends ZipEntry> e = file.entries();
    while (e.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) e.nextElement();

        if (entry.isDirectory()) {
            dirs.add(entry);
        } else {
            files.add(entry);
        }
    }
    for (ZipEntry entry : dirs) {
        File eDir = new File(dirname + "/" + entry.getName());
        eDir.mkdirs();
    }

    for (ZipEntry entry : files) {
        log.debug("Extracting: " + entry);
        unzipEntry(file, entry, dirname);
    }
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

public static PackageSet loadFromZip(ZipFile file) throws IOException, PackageNotFoundException {
    HashMap<String, HashMap<String, InputStream>> setMap = new HashMap<>();
    Enumeration<? extends ZipEntry> entries = file.entries();
    String setName = file.getName().substring(file.getName().lastIndexOf(File.separatorChar) + 1)
            .replace(".zip", "");
    // extract correct entries from the zip file
    while (true) {
        try {//from w  w w .ja  v a 2 s.  c  o m
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // get the correct path separator (both can be used)
            char separator = (entryName.contains("/") ? '/' : '\\');
            // index of first separator used to get set name
            int index = entryName.indexOf(separator);
            // skip entry if there are no path separators (files in zip root like license, readme etc.)
            if (index < 0) {
                continue;
            }
            if (!entryName.endsWith(".yml")) {
                continue;
            }
            String[] parts = entryName.split(Pattern.quote(String.valueOf(separator)));
            String ymlName = parts[parts.length - 1].substring(0, parts[parts.length - 1].length() - 4);
            StringBuilder builder = new StringBuilder();
            int length = parts.length - 1;
            boolean conversation = false;
            if (parts[length - 1].equals("conversations")) {
                length--;
                conversation = true;
            }
            for (int i = 0; i < length; i++) {
                builder.append(parts[i] + '-');
            }
            String packName = builder.substring(0, builder.length() - 1);
            HashMap<String, InputStream> packMap = setMap.get(packName);
            if (packMap == null) {
                packMap = new HashMap<>();
                setMap.put(packName, packMap);
            }
            List<String> allowedNames = Arrays
                    .asList(new String[] { "main", "events", "conditions", "objectives", "journal", "items" });
            if (conversation) {
                packMap.put("conversations." + ymlName, file.getInputStream(entry));
            } else {
                if (allowedNames.contains(ymlName)) {
                    packMap.put(ymlName, file.getInputStream(entry));
                }
            }
        } catch (NoSuchElementException e) {
            break;
        }
    }
    PackageSet set = parseStreams(setName, setMap);
    BetonQuestEditor.getInstance().getSets().add(set);
    RootController.setPackages(BetonQuestEditor.getInstance().getSets());
    return set;
}

From source file:org.nebulaframework.core.job.archive.GridArchive.java

/**
 * Detects all classes inside the given {@code .nar} file and returns an
 * array of fully qualified class name of each class, as {@code String}.
 * //  ww  w .  java2  s.c o  m
 * @param file
 *            {@code .nar File}
 * 
 * @return Fully qualified class names classes in {@code File}
 * 
 * @throws IOException
 *             if occurred during File I/O operations
 */
protected static String[] getAllClassNames(File file) throws IOException {

    // Holds Class Names
    List<String> names = new ArrayList<String>();

    // Create ZipArchive for File
    ZipFile archive = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = archive.entries();

    // Read each entry in archive
    while (entries.hasMoreElements()) {

        ZipEntry entry = entries.nextElement();

        // Ignore Directories
        if (entry.isDirectory())
            continue;

        // Ignore content in NEBULA-INF
        if (entry.getName().startsWith(GridArchive.NEBULA_INF)) {
            continue;
        }

        // Add each file which is a valid class file to list
        if (isClass(entry.getName())) {
            names.add(toClassName(entry.getName()));
        }
    }
    return names.toArray(new String[] {});
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extract(File compressedFile, String export) throws IOException {
    log.trace("Compressed file {}", compressedFile);

    File file = null;/*from w  w  w . ja  v  a2s . com*/
    if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) {
        file = unBZip2(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("tar.gz")) {
        file = unTarGz(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("gz")) {
        file = unGzip(compressedFile);
    } else {
        ZipFile zipFolder = new ZipFile(compressedFile);
        Enumeration<?> enu = zipFolder.entries();

        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();
            long size = zipEntry.getSize();
            long compressedSize = zipEntry.getCompressedSize();
            log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize);

            file = new File(compressedFile.getParentFile() + File.separator + name);
            if (!file.exists() || WdmConfig.getBoolean("wdm.override")) {
                if (name.endsWith("/")) {
                    file.mkdirs();
                    continue;
                }

                File parent = file.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                InputStream is = zipFolder.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();
                file.setExecutable(true);
            } else {
                log.debug(file + " already exists");
            }

        }
        zipFolder.close();
    }

    file = checkPhantom(compressedFile, export);

    log.trace("Resulting binary file {}", file.getAbsoluteFile());
    return file.getAbsoluteFile();
}

From source file:org.kie.guvnor.m2repo.backend.server.GuvnorM2Repository.java

public static String loadPOMFromJar(String jarPath) {
    try {/*from w  ww .  j  a v a  2s .  c  o  m*/
        ZipFile zip = new ZipFile(new File(jarPath));

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

            if (entry.getName().startsWith("META-INF/maven") && entry.getName().endsWith("pom.xml")) {
                InputStream is = zip.getInputStream(entry);

                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                StringBuilder sb = new StringBuilder();
                for (int c = isr.read(); c != -1; c = isr.read()) {
                    sb.append((char) c);
                }
                return sb.toString();
            }
        }
    } catch (ZipException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}