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:com.android.build.gradle.internal.transforms.ExtractJarsTransform.java

private static void extractJar(@NonNull File outJarFolder, @NonNull File jarFile, boolean extractCode)
        throws IOException {
    mkdirs(outJarFolder);/*from ww  w.j a  v a2  s. c  o  m*/
    HashSet<String> lowerCaseNames = new HashSet<>();
    boolean foundCaseInsensitiveIssue = false;

    try (Closer closer = Closer.create()) {
        FileInputStream fis = closer.register(new FileInputStream(jarFile));
        ZipInputStream zis = closer.register(new ZipInputStream(fis));
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            try {
                String name = entry.getName();

                // do not take directories
                if (entry.isDirectory()) {
                    continue;
                }

                foundCaseInsensitiveIssue = foundCaseInsensitiveIssue
                        || !lowerCaseNames.add(name.toLowerCase(Locale.US));

                Action action = getAction(name, extractCode);
                if (action == Action.COPY) {
                    File outputFile = new File(outJarFolder, name.replace('/', File.separatorChar));
                    mkdirs(outputFile.getParentFile());

                    try (Closer closer2 = Closer.create()) {
                        java.io.OutputStream outputStream = closer2
                                .register(new BufferedOutputStream(new FileOutputStream(outputFile)));
                        ByteStreams.copy(zis, outputStream);
                        outputStream.flush();
                    }
                }
            } finally {
                zis.closeEntry();
            }
        }

    }

    if (foundCaseInsensitiveIssue) {
        LOGGER.error(
                "Jar '{}' contains multiple entries which will map to "
                        + "the same file on case insensitive file systems.\n"
                        + "This can be caused by obfuscation with useMixedCaseClassNames.\n"
                        + "This build will be incorrect on case insensitive " + "file systems.",
                jarFile.getAbsolutePath());
    }
}

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

/**
 * unzip a file in the same directory as the zipped file
 * /*w w w  .j a va 2s  .  c o m*/
 * @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:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * @param zipFile/*from ww w . j ava2  s.  c o m*/
 * @param dxpOptions 
 * @return
 * @throws DitaDxpException 
 */
public static ZipEntry getDxpPackageRootMap(ZipFile zipFile, MapBosProcessorOptions dxpOptions)
        throws DitaDxpException {

    List<ZipEntry> candidateRootEntries = new ArrayList<ZipEntry>();
    List<ZipEntry> candidateDirs = new ArrayList<ZipEntry>();

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File temp = new File(entry.getName());
        String parentPath = temp.getParent();
        if (entry.isDirectory()) {
            if (parentPath == null || "".equals(parentPath)) {
                candidateDirs.add(entry);
            }
        } else {
            if (entry.getName().equals("dita_dxp_manifest.ditamap")) {
                return entry;
            }
            if (entry.getName().endsWith(".ditamap")) {
                if (parentPath == null || "".equals(parentPath)) {
                    candidateRootEntries.add(entry);
                }
            }
        }
    }

    // If we get here then we didn't find a manifest map, so look for
    // root map.

    // If exactly one map at the top level, must be the root map of the package.
    if (candidateRootEntries.size() == 1) {
        if (!dxpOptions.isQuiet())
            log.info("Using root map " + candidateRootEntries.get(0).getName());
        return candidateRootEntries.get(0);
    }

    // If there is more than one top-level dir, thank you for playing:

    if (candidateRootEntries.size() == 0 & candidateDirs.size() > 1) {
        throw new DitaDxpException(
                "No manifest map, no map in root of package, and more than one top-level directory in package.");
    }

    // If there is exactly one root directory, look in it for exactly one map:
    if (candidateDirs.size() == 1) {
        String parentPath = candidateDirs.get(0).getName();
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File temp = new File(entry.getName());
            String entryParent = temp.getParent();
            if (entryParent == null)
                entryParent = "/";
            else
                entryParent += "/";
            if (parentPath.equals(entryParent) && entry.getName().endsWith(".ditamap")) {
                candidateRootEntries.add(entry);
            }
        }
        if (candidateRootEntries.size() == 1) {
            // Must be the root map
            if (!dxpOptions.isQuiet())
                log.info("Using root map " + candidateRootEntries.get(0).getName());
            return candidateRootEntries.get(0);
        }
        if (candidateRootEntries.size() > 1) {
            throw new DitaDxpException(
                    "No manifest map and found more than one map in the root directory of the package.");
        }
    }

    // Should never get here:

    throw new DitaDxpException("Unable to find package manifest map or single root map in DXP package.");

}

From source file:Main.java

public static void unzipEPub(String inputZip, String destinationDirectory) throws IOException {
    int BUFFER = 2048;
    List zipFiles = new ArrayList();
    File sourceZipFile = new File(inputZip);
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdir();/*from   www. j  a  v  a2s .co  m*/

    ZipFile zipFile;
    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {

        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        if (currentEntry.endsWith(".zip")) {
            zipFiles.add(destFile.getAbsolutePath());
        }

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;
            // buffer for writing file
            byte data[] = new byte[BUFFER];

            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();

        }

    }
    zipFile.close();

    for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
        String zipName = (String) iter.next();
        unzipEPub(zipName,
                destinationDirectory + File.separatorChar + zipName.substring(0, zipName.lastIndexOf(".zip")));
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given apk into the given destination directory
 * //ww  w . java 2  s . c  o  m
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws IOException
 */
public static void extractApk(File archive, File dest) throws IOException {

    @SuppressWarnings("resource") // Closing it later results in an error
    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;

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

        String entryFileName = entry.getName();

        byte[] buffer = new byte[16384];
        int len;

        File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {
            if (entry.getSize() == 0) {
                LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName()
                        + ". Looks corrupted.");
                continue;
            }

            try {
                bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,...

                bis = new BufferedInputStream(zipFile.getInputStream(entry));

                while ((len = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            } catch (IOException ioe) {
                LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for "
                        + archive.getName() + " may not be accurate");
            } finally {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
                // if (zipFile != null) zipFile.close();
            }
        }

    }

}

From source file:com.esofthead.mycollab.jetty.GenericServerRunner.java

private static void unpackFile(File upgradeFile) throws IOException {
    File libFolder = new File(System.getProperty("user.dir"), "lib");
    File webappFolder = new File(System.getProperty("user.dir"), "webapp");
    org.apache.commons.io.FileUtils.deleteDirectory(libFolder);
    org.apache.commons.io.FileUtils.deleteDirectory(webappFolder);

    byte[] buffer = new byte[2048];

    try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(upgradeFile))) {
        ZipEntry entry;
        while ((entry = inputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()
                    && (entry.getName().startsWith("lib/") || entry.getName().startsWith("webapp"))) {
                File candidateFile = new File(System.getProperty("user.dir"), entry.getName());
                candidateFile.getParentFile().mkdirs();
                try (FileOutputStream output = new FileOutputStream(candidateFile)) {
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, len);
                    }// w w  w.j a  v  a2  s.  com
                }
            }
        }
    } catch (IOException e) {
        throw new MyCollabException(e);
    }
}

From source file:com.asakusafw.bulkloader.testutil.UnitTestUtil.java

public static boolean assertZipFile(File[] expectedFile, File zipFile) throws IOException {

    ZipInputStream zipIs = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry zipEntry = null;
    int i = 0;//from  w  w  w.  j a v  a  2 s  . c o m
    while ((zipEntry = zipIs.getNextEntry()) != null) {
        if (zipEntry.isDirectory()) {
            continue;
        }
        i++;
        File tempFile = new File("target/asakusa-thundergate/tempdata" + String.valueOf(i));
        FileOutputStream fos = new FileOutputStream(tempFile);
        byte[] b = new byte[1024];
        while (true) {
            int read = zipIs.read(b);
            if (read == -1) {
                break;
            }
            fos.write(b, 0, read);
        }

        // ?
        if (!assertFile(expectedFile[i - 1], tempFile)) {
            tempFile.delete();
            return false;
        }

        // temp
        tempFile.delete();
    }
    return true;
}

From source file:com.ikon.util.ReportUtils.java

/**
 * Execute report//from   w w  w.j  av  a 2  s. co m
 */
public static ByteArrayOutputStream execute(Report rp, final Map<String, Object> params, final int format)
        throws JRException, IOException, EvalError {
    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;
    ZipInputStream zis = null;
    Session dbSession = null;

    try {
        baos = new ByteArrayOutputStream();
        bais = new ByteArrayInputStream(SecureStore.b64Decode(rp.getFileContent()));
        JasperReport jr = null;

        // Obtain or compile report
        if (ReportUtils.MIME_JRXML.equals(rp.getFileMime())) {
            log.debug("Report type: JRXML");
            jr = JasperCompileManager.compileReport(bais);
        } else if (ReportUtils.MIME_JASPER.equals(rp.getFileMime())) {
            log.debug("Report type: JASPER");
            jr = (JasperReport) JRLoader.loadObject(bais);
        } else if (ReportUtils.MIME_REPORT.equals(rp.getFileMime())) {
            zis = new ZipInputStream(bais);
            ZipEntry zi = null;

            while ((zi = zis.getNextEntry()) != null) {
                if (!zi.isDirectory()) {
                    String mimeType = MimeTypeConfig.mimeTypes.getContentType(zi.getName());

                    if (ReportUtils.MIME_JRXML.equals(mimeType)) {
                        log.debug("Report type: JRXML inside ARCHIVE");
                        jr = JasperCompileManager.compileReport(zis);
                        break;
                    } else if (ReportUtils.MIME_JASPER.equals(mimeType)) {
                        log.debug("Report type: JASPER inside ARCHIVE");
                        jr = (JasperReport) JRLoader.loadObject(zis);
                        break;
                    }
                }
            }
        }

        // Guess if SQL or BSH
        if (jr != null) {
            JRQuery query = jr.getQuery();
            String tq = query.getText().trim();

            if (tq.toUpperCase().startsWith("SELECT")) {
                log.debug("Report type: DATABASE");
                dbSession = HibernateUtil.getSessionFactory().openSession();
                executeDatabase(dbSession, baos, jr, params, format);
            } else {
                log.debug("Report type: SCRIPTING");
                ReportUtils.generateReport(baos, jr, params, format);
            }
        }

        return baos;
    } finally {
        HibernateUtil.close(dbSession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(zis);
    }
}

From source file:org.canova.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to/*w  ww.  j  ava 2 s  .co m*/
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

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

/** Unzip a zipFile into a directory.  This will create subdirectories
 * as needed.//w w w  .j a v  a2 s. c o  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);
    }
}