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.mgmtp.perfload.perfalyzer.util.IoUtilities.java

/**
 * Unzips a zip file./*from  w w w . j  a va  2 s  . c  o  m*/
 *
 * @param zip
 *       the zip file
 * @param destDir
 *       the destination directory (will be created if non-existent)
 */
public static void unzip(final ZipFile zip, final File destDir) throws IOException {
    if (!destDir.exists()) {
        destDir.mkdir();
    }

    for (Enumeration<? extends ZipEntry> zipEntryEnum = zip.entries(); zipEntryEnum.hasMoreElements();) {
        ZipEntry zipEntry = zipEntryEnum.nextElement();
        extractEntry(zip, zipEntry, destDir);
    }
}

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

public static IProject importTestProject(String projectName, File file)
        throws CoreException, ZipException, IOException, InvocationTargetException, InterruptedException {
    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;/*from   w  w  w.  java 2s  .com*/
    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:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//w  w w.ja  v a 2 s. co m

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

                String mime = new Tika().detect(newFile);
                if (mime.equals("application/x-sh") || mime.startsWith("text/"))
                    FileUtils.writeLines(newFile, FileUtils.readLines(newFile));

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:azkaban.utils.Utils.java

public static void unzip(ZipFile source, File dest) throws IOException {
    Enumeration<?> entries = source.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        File newFile = new File(dest, entry.getName());
        if (entry.isDirectory()) {
            newFile.mkdirs();//from   w w w.ja  va2 s .  c  o  m
        } else {
            newFile.getParentFile().mkdirs();
            InputStream src = source.getInputStream(entry);
            try {
                OutputStream output = new BufferedOutputStream(new FileOutputStream(newFile));
                try {
                    IOUtils.copy(src, output);
                } finally {
                    output.close();
                }
            } finally {
                src.close();
            }
        }
    }
}

From source file:com.simiacryptus.mindseye.lang.Layer.java

/**
 * From zip nn key.//from www. j  ava2  s.co m
 *
 * @param zipfile the zipfile
 * @return the nn key
 */
@Nonnull
static Layer fromZip(@Nonnull final ZipFile zipfile) {
    Enumeration<? extends ZipEntry> entries = zipfile.entries();
    @Nullable
    JsonObject json = null;
    @Nonnull
    HashMap<CharSequence, byte[]> resources = new HashMap<>();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        CharSequence name = zipEntry.getName();
        try {
            InputStream inputStream = zipfile.getInputStream(zipEntry);
            if (name.equals("model.json")) {
                json = new GsonBuilder().create().fromJson(new InputStreamReader(inputStream),
                        JsonObject.class);
            } else {
                resources.put(name, IOUtils.readFully(inputStream, (int) zipEntry.getSize()));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return fromJson(json, resources);
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Compress the files in the backup folder for a project.
 * @param projectId The project ID/* w  w w  .  ja va  2s  . c o  m*/
 * @throws IOException Any exception when reading/writing data.
 */
public static void compressBackupFolder(final String projectId) throws IOException {
    String backupPath = getBackupPath(projectId);
    if (!Files.isDirectory(Paths.get(backupPath))) {
        // No such directory, so nothing to do.
        return;
    }
    String projectSlug = makeSlug(projectId);
    // The name of the ZIP file that does/will contain all
    // backups for this project.
    Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
    // A temporary ZIP file. Any existing content in the zipFilePath
    // will be copied into this, followed by any other files in
    // the directory that have not yet been added.
    Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");

    File tempZipFile = tempZipFilePath.toFile();
    if (!tempZipFile.exists()) {
        tempZipFile.createNewFile();
    }

    ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile));

    File existingZipFile = zipFilePath.toFile();
    if (existingZipFile.exists()) {
        ZipFile zipIn = new ZipFile(existingZipFile);

        Enumeration<? extends ZipEntry> entries = zipIn.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            logger.debug("compressBackupFolder copying: " + e.getName());
            tempZipOut.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(zipIn.getInputStream(e), tempZipOut);
            }
            tempZipOut.closeEntry();
        }
        zipIn.close();
    }

    File dir = new File(backupPath);
    File[] files = dir.listFiles();

    for (File source : files) {
        if (!source.getName().toLowerCase().endsWith(".zip")) {
            logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString());
            if (zipFile(tempZipOut, source)) {
                source.delete();
            }
        }
    }

    tempZipOut.flush();
    tempZipOut.close();
    tempZipFile.renameTo(existingZipFile);
}

From source file:com.impetus.ankush.common.utils.FileNameUtils.java

/**
 * Gets the extracted directory name.//  ww  w . java 2 s .  c om
 * 
 * @param archiveFile
 *            the archive file
 * @return Directory name after extraction of archiveFile
 */
public static String getExtractedDirectoryName(String archiveFile) {
    String path = null;
    ONSFileType fileType = getFileType(archiveFile);

    if (fileType == ONSFileType.TAR_GZ || fileType == ONSFileType.GZ) {
        try {
            GZIPInputStream gzipInputStream = null;
            gzipInputStream = new GZIPInputStream(new FileInputStream(archiveFile));
            TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipInputStream);

            return tarInput.getNextTarEntry().getName();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    } else if (fileType == ONSFileType.ZIP || fileType == ONSFileType.BIN) {
        ZipFile zf;
        try {
            zf = new ZipFile(archiveFile);
            Enumeration<? extends ZipEntry> entries = zf.entries();

            return entries.nextElement().getName();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    return path;
}

From source file:com.gisgraphy.domain.geoloc.importer.ImporterHelper.java

/**
 * unzip a file in the same directory as the zipped file
 * //  w  ww. j  a  v a  2s  . c om
 * @param file
 *            The file to unzip
 */
public static void unzipFile(File file) {
    logger.info("will Extracting file: " + file.getName());
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile;

    try {
        zipFile = new ZipFile(file);

        entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (entry.isDirectory()) {
                // Assume directories are stored parents first then
                // children.
                (new File(entry.getName())).mkdir();
                continue;
            }

            logger.info("Extracting file: " + entry.getName() + " to " + file.getParent() + File.separator
                    + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(file.getParent() + File.separator + entry.getName())));
        }

        zipFile.close();
    } catch (IOException e) {
        logger.error("can not unzip " + file.getName() + " : " + e.getMessage());
        throw new ImporterException(e);
    }
}

From source file:org.apache.synapse.libraries.util.LibDeployerUtils.java

private static void extract(String sourcePath, String destPath) throws IOException {
    Enumeration entries;//from  w  ww  . j a va 2s .  com
    ZipFile zipFile;

    zipFile = new ZipFile(sourcePath);
    entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        // we don't need to copy the META-INF dir
        if (entry.getName().startsWith("META-INF/")) {
            continue;
        }
        // if the entry is a directory, create a new dir
        if (entry.isDirectory()) {
            createDir(destPath + entry.getName());
            continue;
        }
        // if the entry is a file, write the file
        copyInputStream(zipFile.getInputStream(entry),
                new BufferedOutputStream(new FileOutputStream(destPath + entry.getName())));
    }
    zipFile.close();
}

From source file:com.impetus.ankush.common.utils.FileNameUtils.java

/**
 * Gets the path from archive.//from   www .j av  a  2s  .c o  m
 * 
 * @param archiveFile
 *            the archive file
 * @param charSequence
 *            the char sequence
 * @return the path from archive
 */
public static String getPathFromArchive(String archiveFile, String charSequence) {
    String path = null;
    ONSFileType fileType = getFileType(archiveFile);

    if (fileType == ONSFileType.TAR_GZ) {
        try {
            GZIPInputStream gzipInputStream = null;
            gzipInputStream = new GZIPInputStream(new FileInputStream(archiveFile));
            TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipInputStream);

            TarArchiveEntry entry;
            while (null != (entry = tarInput.getNextTarEntry())) {
                if (entry.getName().contains(charSequence)) {
                    path = entry.getName();
                    break;
                }
            }

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    } else if (fileType == ONSFileType.ZIP) {
        ZipFile zf;
        try {
            zf = new ZipFile(archiveFile);
            Enumeration<? extends ZipEntry> entries = zf.entries();
            String fileName;
            while (entries.hasMoreElements()) {
                fileName = entries.nextElement().getName();
                if (fileName.contains(charSequence)) {
                    path = fileName;
                    break;
                }
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    return path;
}