Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * The raw structure of all projects is contained in a zip file. This
 * method inflates this file in a temporary folder.
 * @throws IOException/*w ww .ja  va  2s  . com*/
 */
public void inflateProjects() throws IOException {
    FileUtils.forceMkdir(tmpDst);
    FileUtils.cleanDirectory(tmpDst);

    InputStream is = Res.getStream("projects.zip");
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;

    while ((entry = zis.getNextEntry()) != null) {
        File file = new File(tmpDst, entry.getName());
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream os = new FileOutputStream(file);
            IOUtils.copy(zis, os);
            os.close();
        }
    }

    zis.close();
}

From source file:com.isomorphic.maven.packaging.Distribution.java

/**
 * Extract the relevant contents from each file in the distribution.  Additionally creates ZIP/JAR
 * files from specified resources (e.g., javadoc).
 * /*from w ww  .j  a va2 s. co m*/
 * @param to The directory to which each file should be extracted.
 * @throws IOException
 */
public void unpack(File to) throws IOException {

    outer: for (File file : files) {

        String ext = FilenameUtils.getExtension(file.getName()).toUpperCase();

        //copy uncompressed files to target, renaming as necessary per 'contents' configuration
        if (!"ZIP".equals(ext)) {
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(file.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey()));
                    FileUtils.copyFile(file, target);
                    LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath());
                    continue outer;
                }
            }
            FileUtils.copyFileToDirectory(file, new File(to, "lib"));
            continue outer;
        }

        //otherwise extract contents (again renaming / relocating contents as necessary)
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(entry.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey()));
                    FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target);
                    LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath());
                }
            }
        }
        zip.close();
    }

    /*
     * Create any number of assemblies by dropping their resources here.
     * Each subdirectory will get zipped up and then deleted
     */
    File assembliesDir = new File(to, "assembly");

    @SuppressWarnings("unchecked")
    Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File arg0) {
            return arg0.isDirectory();
        }
    }));
    for (File assembly : assemblies) {
        String name = FilenameUtils.getBaseName(assembly.getName());
        LOGGER.debug("Copying resources for assembly '{}'", name);
        ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip"));
        FileUtils.deleteQuietly(assembly);
    }

    LOGGER.debug("Repackaging Javadoc...");
    File docLib = new File(to, "doc/lib");

    //TODO these paths should probably all be stuck in some constant
    File client = FileUtils.getFile(to, "doc/api/client");
    if (client.exists()) {
        ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar"));
    }

    File server = FileUtils.getFile(to, "doc/api/server");
    if (server.exists()) {
        ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar"));
    }
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Searches ZIP archive and returns properties found in "META-INF/maven/archetype-metadata.xml" entry
 *
 * @return//from  ww  w  .j  a va 2  s. c o m
 * @throws IOException
 */
public Map<String, String> parseProperties() throws IOException {
    Map<String, String> replaceProperties = new HashMap<String, String>();
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(archetypeIn);
        boolean ok = true;
        while (ok) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                ok = false;
            } else {
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) {
                        parseReplaceProperties(zip, replaceProperties);
                    }
                }
                zip.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (zip != null) {
            zip.close();
        }
    }
    return replaceProperties;
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the uncompression of a <code>zip</code> file, whose name and
 * parent directory are passed as arguments, on the local filesystem. The
 * content of the <code>zip</code> file will be uncompressed within a
 * specified target directory.<br>
 *
 * @param srcDirectory/*  w  ww .  j av a 2s . c o m*/
 *            the source parent directory of the file/s to be unzipped. Must
 *            be an absolute pathname.
 * @param zipFilename
 *            the name of the file to be unzipped. Cannot contain wildcards.
 * @param targetDirectory
 *            the target directory in which the content of the
 *            <code>zip</code> file will be unzipped. Must be an absolute
 *            pathname.
 * @throws IOException
 *             If any error occurs during file uncompression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void unzipFile(String srcDirectory, String zipFilename, String targetDirectory) throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File srcZipFile = new File(srcDirectory, zipFilename);
    if (!srcZipFile.exists()) {
        throw new IllegalArgumentException(
                "File to be unzipped (" + srcZipFile.getAbsolutePath() + ") NOT found on local filesystem.");
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(srcZipFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry currEntry = entries.nextElement();
            if (currEntry.isDirectory()) {
                String targetSubdirPathname = currEntry.getName();
                File dir = new File(targetDirectory, targetSubdirPathname);
                FileUtils.forceMkdir(dir);
                dir.setLastModified(currEntry.getTime());
            } else {
                InputStream is = null;
                OutputStream os = null;
                File file = null;
                try {
                    is = zipFile.getInputStream(currEntry);
                    FileUtils.forceMkdir(new File(targetDirectory, currEntry.getName()).getParentFile());
                    file = new File(targetDirectory, currEntry.getName());
                    os = new FileOutputStream(file);
                    IOUtils.copy(is, os);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }

                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException exc) {
                        // Do nothing
                    }

                    if (file != null) {
                        file.setLastModified(currEntry.getTime());
                    }
                }
            }
        }
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (Exception exc) {
            // do nothing
        }
    }
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Unzips the supplied zip file//  www. j  a v  a  2 s .c  om
 * 
 * @param zip
 *            The zip file to extract
 * @param destinationDir
 *            the directory to extract the zip to
 * @throws IOException
 *             if an error occurred while extracting the zip file.
 */
public static void extractZipFile(File zip, File destinationDir) throws IOException {
    if (!zip.exists()) {
        throw new IllegalArgumentException("zip file does not exist");
    }

    if (!zip.isFile()) {
        throw new IllegalArgumentException("supplied zip file is not a file");
    }

    if (!destinationDir.exists()) {
        throw new IllegalArgumentException("destination does not exist");
    }

    if (!destinationDir.isDirectory()) {
        throw new IllegalArgumentException("destination is not a directory");
    }

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

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

        File fileForEntry = new File(destinationDir, entryName);
        if (entry.isDirectory() && !fileForEntry.exists()) {
            fileForEntry.mkdirs();
        } else {
            InputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            FileUtils.copyInputStreamToFile(is, fileForEntry);
        }
    }
}

From source file:com.ery.hadoop.mrddx.file.LineReaders.java

/**
 * Read one line from the InputStream into the given Text.
 * /*from   w w w  .j  a  v  a2  s  . c o  m*/
 * @param str
 *            the object to store the given line (without newline)
 * @param maxLineLength
 *            the maximum number of bytes to store into str; the rest of the
 *            line is silently discarded.
 * @param maxBytesToConsume
 *            the maximum number of bytes to consume in this call. This is
 *            only a hint, because if the line cross this threshold, we
 *            allow it to happen. It can overshoot potentially by as much as
 *            one buffer length.
 * 
 * @return the number of bytes read including the (longest) newline found.
 * 
 * @throws IOException
 *             if the underlying stream throws
 */
public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException {
    int readsize = -1;
    if (!isreadtar) {
        isreadtar = true;
        if (in instanceof TarInputStream) {// ?tar
            TarEntry te = ((TarInputStream) in).getNextEntry();
            System.out.print("input stream is TarInputStream  getNextEntry:");
            while (te != null && te.isDirectory()) {
                LOG.info(" dir: " + te.getName());
                te = ((TarInputStream) in).getNextEntry();
            }
            if (te == null)
                return -1;
            contextFileName = te.getName();
            LOG.info(" file: " + contextFileName);
        } else if (in instanceof ZipInputStream) {
            System.out.print("input stream is ZipInputStream  getNextEntry:");
            ZipEntry zin = ((ZipInputStream) in).getNextEntry();
            while (zin != null && zin.isDirectory()) {
                LOG.info(" dir: " + zin.getName());
                zin = ((ZipInputStream) in).getNextEntry();
            }
            if (zin == null)
                return -1;
            contextFileName = zin.getName();
            LOG.info(" file: " + contextFileName);
        }
    }
    if (this.recordDelimiterBytes != null) {
        readsize = readCustomLine(str, maxLineLength, maxBytesToConsume);
    } else {
        readsize = readDefaultLine(str, maxLineLength, maxBytesToConsume);
    }

    while (readsize <= 0) {
        if (in instanceof TarInputStream) {// do tar header
            TarEntry te = ((TarInputStream) in).getNextEntry();
            System.out.print("input stream is TarInputStream  getNextEntry:");
            while (te != null && te.isDirectory()) {
                LOG.info(" dir: " + te.getName());
                te = ((TarInputStream) in).getNextEntry();
            }
            if (te == null)
                return -1;
            LOG.info(" file: " + te.getName());
            if (this.perFileSkipRowNum > 0 && !skipFileNum(str, maxLineLength, maxBytesToConsume))
                return -1;
        } else if (in instanceof ZipInputStream) {
            System.out.print("input stream is ZipInputStream  getNextEntry:");
            ZipEntry zin = ((ZipInputStream) in).getNextEntry();
            while (zin != null && zin.isDirectory()) {
                LOG.info(" dir: " + zin.getName());
                zin = ((ZipInputStream) in).getNextEntry();
            }
            if (zin == null)
                return -1;
            if (this.perFileSkipRowNum > 0 && !skipFileNum(str, maxLineLength, maxBytesToConsume))
                return -1;
            LOG.info(" file: " + zin.getName());
        } else {
            break;
        }
        if (this.recordDelimiterBytes != null) {
            readsize = readCustomLine(str, maxLineLength, maxBytesToConsume);
        } else {
            readsize = readDefaultLine(str, maxLineLength, maxBytesToConsume);
        }
    }
    return readsize;
}

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * libs folders of the projects./*ww  w .  j  a va 2 s  .co  m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(tmpDst, "/prj-common/libs");
    File desktopPrjLibsDir = new File(tmpDst, "/prj-desktop/libs");
    File androidPrjLibsDir = new File(tmpDst, "/prj-android/libs");
    File htmlPrjLibsDir = new File(tmpDst, "/prj-html/war/WEB-INF/lib");
    File iosPrjLibsDir = new File(tmpDst, "/prj-ios/libs");
    File dataDir = new File(tmpDst, "/prj-android/assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);
            for (String elemName : def.libsDesktop)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, desktopPrjLibsDir);
            for (String elemName : def.libsAndroid)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, androidPrjLibsDir);
            for (String elemName : def.libsHtml)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, htmlPrjLibsDir);
            for (String elemName : def.libsIos)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, iosPrjLibsDir);
            for (String elemName : def.data)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, dataDir);
        }

        zis.close();
    }
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

/**
 * Unzip the specified file.//from w  ww. j a  va2  s  .c  om
 * 
 * @param zipFilePath String path to zip file.
 * @throws IOException during zip or read process.
 */
public static void extractFolder(String zipFilePath) throws IOException {
    ZipFile zipFile = null;

    try {
        int BUFFER = 2048;
        File file = new File(zipFilePath);

        zipFile = new ZipFile(file);
        String newPath = zipFilePath.substring(0, zipFilePath.length() - 4);

        makeDirs(new File(newPath));
        Enumeration<?> zipFileEntries = zipFile.entries();

        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            File destinationParent = destFile.getParentFile();

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

            InputStream is = null;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;

            try {
                if (destFile.exists() && destFile.isDirectory())
                    continue;

                if (!entry.isDirectory()) {
                    int currentByte;
                    byte data[] = new byte[BUFFER];
                    is = zipFile.getInputStream(entry);
                    bis = new BufferedInputStream(is);
                    fos = new FileOutputStream(destFile);
                    bos = new BufferedOutputStream(fos, BUFFER);

                    while ((currentByte = bis.read(data, 0, BUFFER)) != -1) {
                        bos.write(data, 0, currentByte);
                    }
                    bos.flush();
                }
            } finally {
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(bos);
                IOUtils.closeQuietly(fos);
            }

            if (currentEntry.endsWith(".zip")) {
                extractFolder(destFile.getAbsolutePath());
            }
        }
    } catch (Exception e) {
        log.warning("Failed to unzip: " + zipFilePath, e);
        throw new IllegalStateException(e);
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
}

From source file:com.yahoo.storm.yarn.TestConfig.java

private void unzipFile(String filePath) {
    FileInputStream fis = null;//from  w w w  .  j av a  2s  . co m
    ZipInputStream zipIs = null;
    ZipEntry zEntry = null;
    try {
        fis = new FileInputStream(filePath);
        zipIs = new ZipInputStream(new BufferedInputStream(fis));
        while ((zEntry = zipIs.getNextEntry()) != null) {
            try {
                byte[] tmp = new byte[4 * 1024];
                FileOutputStream fos = null;
                String opFilePath = "lib/" + zEntry.getName();
                if (zEntry.isDirectory()) {
                    LOG.debug("Create a folder " + opFilePath);
                    if (zEntry.getName().indexOf(Path.SEPARATOR) == (zEntry.getName().length() - 1))
                        storm_home = opFilePath.substring(0, opFilePath.length() - 1);
                    new File(opFilePath).mkdir();
                } else {
                    LOG.debug("Extracting file to " + opFilePath);
                    fos = new FileOutputStream(opFilePath);
                    int size = 0;
                    while ((size = zipIs.read(tmp)) != -1) {
                        fos.write(tmp, 0, size);
                    }
                    fos.flush();
                    fos.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        zipIs.close();
    } catch (FileNotFoundException e) {
        LOG.warn(e.toString());
    } catch (IOException e) {
        LOG.warn(e.toString());
    }
    LOG.info("storm_home: " + storm_home);
}

From source file:org.adempiere.webui.install.WTranslationDialog.java

private void unZipAndProcess(InputStream istream) throws AdempiereException {
    FileOutputStream ostream = null;
    File file = null;//w w w. ja v  a 2 s .c  o  m
    try {
        file = File.createTempFile("trlImport", ".zip");
        ostream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int read;
        while ((read = istream.read(buffer)) != -1) {
            ostream.write(buffer, 0, read);
        }
    } catch (Throwable e) {
        throw new AdempiereException("Copy zip failed", e);
    } finally {
        if (ostream != null) {
            try {
                ostream.close();
            } catch (Exception e2) {
            }
        }
    }

    // create temp folder
    File tempfolder;
    try {
        tempfolder = File.createTempFile(m_AD_Language.getValue(), ".trl");
        tempfolder.delete();
        tempfolder.mkdir();
    } catch (IOException e1) {
        throw new AdempiereException("Problem creating temp folder", e1);
    }

    String suffix = "_" + m_AD_Language.getValue() + ".xml";
    ZipFile zipFile = null;
    boolean validfile = false;
    try {
        zipFile = new ZipFile(file);

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

            if (entry.isDirectory()) {
                // ignore folders
                log.warning("Imported zip must not contain folders, ignored folder" + entry.getName());
                continue;
            }

            if (!entry.getName().endsWith(suffix)) {
                // not valid file
                log.warning("Ignored file " + entry.getName());
                continue;
            }

            if (log.isLoggable(Level.INFO))
                log.info("Extracting file: " + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(tempfolder.getPath() + File.separator + entry.getName())));
            validfile = true;
        }
    } catch (Throwable e) {
        throw new AdempiereException("Uncompress zip failed", e);
    } finally {
        if (zipFile != null)
            try {
                zipFile.close();
            } catch (IOException e) {
            }
    }

    if (!validfile) {
        throw new AdempiereException("ZIP file invalid, doesn't contain *" + suffix + " files");
    }

    callImportProcess(tempfolder.getPath());

    file.delete();
    try {
        FileUtils.deleteDirectory(tempfolder);
    } catch (IOException e) {
    }
}