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:net.technicpack.launchercore.util.ZipUtils.java

/**
 * Unzips a file into the specified directory.
 *
 * @param zip          file to unzip//from   w ww. ja v a 2 s .c  om
 * @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:com.dv.util.DataViewerZipUtil.java

public static void doUnzipFile(ZipFile zipFile, File dest) throws IOException {
    if (!dest.exists()) {
        FileUtils.forceMkdir(dest);//from  w w w  . ja  v  a  2  s.  c  o  m
    }
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (entry.getName().endsWith(File.separator)) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream out = FileUtils.openOutputStream(file);
            InputStream in = zipFile.getInputStream(entry);
            try {
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }
    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 www .ja v a  2 s  .  c o  m
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.pieframework.runtime.utils.Zipper.java

public static void unzip(String zipFile, String toDir) throws ZipException, IOException {

    int BUFFER = 2048;
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);
    String newPath = toDir;//from w  w  w .ja v  a  2  s .  co  m

    File toDirectory = new File(newPath);
    if (!toDirectory.exists()) {
        toDirectory.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, FilenameUtils.separatorsToSystem(currentEntry));
        //System.out.println(currentEntry);
        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
            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();
        }
    }
    zip.close();

}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory./*from w ww. j  a  v  a 2s .co  m*/
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                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);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

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

private static Predicate<String> getNoCompressPredicate(String srcPath) throws IOException {
    Set<String> noCompressEntries = new HashSet<>();
    ZipFile zipFile = new ZipFile(srcPath);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        if (zipEntry.getMethod() == 0) {
            if (zipEntry.getName().endsWith(".so")) {
                nativeLibrariesPackagingMode = NativeLibrariesPackagingMode.UNCOMPRESSED_AND_ALIGNED;
            }/*from   w  ww .  j  a  v a2  s.c o m*/
            noCompressEntries.add(zipEntry.getName());
        }
    }
    return s -> noCompressEntries.contains(s);
}

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());
        }/*from w  w  w .ja  v  a  2  s  .c  o  m*/
    }
    return s -> paths.contains(s);

}

From source file:org.eclipse.vjet.testframework.artifactmanager.project.ProjectArtifactManager.java

public static String unzipProject(File zipFile, File destDir, String projectName) throws IOException {
    if (!TestUtils.isDirectoryWritable(destDir, true)) {
        return "unable to create writable directory: " + destDir;
    }// www .  j a v a2 s .  c  o  m
    if (!TestUtils.isFileReadable(zipFile)) {
        return "no readable file: " + zipFile;
    }

    ZipFile zip = null;
    String projectEntryName = "projects" + "/" + projectName;
    try {
        zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory() && entry.getName().startsWith(projectEntryName)) {
                File destFile = new File(destDir, entry.getName());
                InputStream src = null;
                try {
                    src = zip.getInputStream(entry);
                    String result = TestUtils.write(src, destFile);
                    if (null != result) {
                        return result;
                    }
                } finally {
                    if (null != src) {
                        src.close();
                    }
                }
            }
        }
    } finally {
        if (null != zip) {
            zip.close();
        }
    }
    return null;
}

From source file:org.jboss.tools.maven.sourcelookup.test.OpenBinaryFile.java

public static IProject importTestProject(File file)
        throws CoreException, ZipException, IOException, InvocationTargetException, InterruptedException {
    final String projectName = PROJECT_NAME;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IProject project = workspace.getRoot().getProject(projectName);
    createProject(project, new NullProgressMonitor());
    project.open(new NullProgressMonitor());
    ZipFile sourceFile = new ZipFile(file);
    ZipLeveledStructureProvider structureProvider = new ZipLeveledStructureProvider(sourceFile);

    Enumeration<? extends ZipEntry> entries = sourceFile.entries();
    ZipEntry entry = null;/*  ww  w . j a va  2s .c  o m*/
    List<ZipEntry> filesToImport = new ArrayList<ZipEntry>();
    List<ZipEntry> directories = new ArrayList<ZipEntry>();
    String prefix = projectName + "/"; //$NON-NLS-1$
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        if (entry.getName().startsWith(prefix)) {
            if (!entry.isDirectory()) {
                filesToImport.add(entry);
            } else {
                directories.add(entry);
            }
        }
    }

    structureProvider.setStrip(1);
    ImportOperation operation = new ImportOperation(project.getFullPath(), structureProvider.getRoot(),
            structureProvider, OVERWRITE_ALL_QUERY, filesToImport);
    operation.setContext(getActiveShell());
    operation.run(new NullProgressMonitor());
    for (ZipEntry directory : directories) {
        IPath resourcePath = new Path(directory.getName());
        if (resourcePath.segmentCount() > 1 && !workspace.getRoot().getFolder(resourcePath).exists()) {
            workspace.getRoot().getFolder(resourcePath).create(false, true, null);
        }
    }
    return project;
}

From source file:ClassFinder.java

private static void findClassesInOnePath(String strPath, Set<String> listClasses) throws IOException {
    File file = new File(strPath);
    if (file.isDirectory()) {
        findClassesInPathsDir(strPath, file, listClasses);
    } else if (file.exists()) {
        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));
            }/*from  ww w . jav  a 2 s .co  m*/
        }
        zipFile.close();
    }
}