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:de.langmi.spring.batch.examples.readers.file.zip.ZipMultiResourceItemReader.java

/**
 * Extract only files from the zip archive.
 *
 * @param currentZipFile/*from w  ww.  j  a  va 2  s .co  m*/
 * @param extractedResources
 * @throws IOException 
 */
private static void extractFiles(final ZipFile currentZipFile, final List<Resource> extractedResources)
        throws IOException {
    Enumeration<? extends ZipEntry> zipEntryEnum = currentZipFile.entries();
    while (zipEntryEnum.hasMoreElements()) {
        ZipEntry zipEntry = zipEntryEnum.nextElement();
        LOG.info("extracting:" + zipEntry.getName());
        // traverse directories
        if (!zipEntry.isDirectory()) {
            // add inputStream
            extractedResources
                    .add(new InputStreamResource(currentZipFile.getInputStream(zipEntry), zipEntry.getName()));
            LOG.info("using extracted file:" + zipEntry.getName());
        }
    }
}

From source file:Main.java

public static void unzip(InputStream fin, String targetPath, Context context) throws IOException {
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fin));
    try {/*from  www .ja v  a2 s. com*/
        ZipEntry zipEntry;
        int count;
        byte[] buffer = new byte[8192];
        while ((zipEntry = zis.getNextEntry()) != null) {
            File file = new File(targetPath, zipEntry.getName());
            File dir = zipEntry.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                throw new FileNotFoundException("Failed to get directory: " + dir.getAbsolutePath());
            }
            if (zipEntry.isDirectory()) {
                continue;
            }
            FileOutputStream fout = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1)
                    fout.write(buffer, 0, count);
            } finally {
                fout.close();
            }
            Log.d("TEST", "Unzipped " + file.getAbsolutePath());
        }
    } finally {
        zis.close();
    }
}

From source file:ch.admin.suis.msghandler.util.ZipUtils.java

/**
 * Decompress the given file to the specified directory.
 *
 * @param zipFile the ZIP file to decompress
 * @param toDir   the directory where the files from the archive must be placed; the
 *                file will be replaced if it already exists
 * @return a list of files that were extracted into the destination directory
 * @throws IllegalArgumentException if the provided file does not exist or the specified destination
 *                                  is not a directory
 * @throws IOException              if an IO error has occured (probably, a corrupted ZIP file?)
 *//*from w ww .  j av  a2s. c  om*/
public static List<File> decompress(File zipFile, File toDir) throws IOException {
    Validate.isTrue(zipFile.exists(), "ZIP file does not exist", zipFile.getAbsolutePath());
    Validate.isTrue(toDir.isDirectory(), toDir.getAbsolutePath() + " is not a directory");

    final ArrayList<File> files = new ArrayList<>();

    try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)))) {

        // read the entries
        ZipEntry entry;
        while (null != (entry = zis.getNextEntry())) {
            if (entry.isDirectory()) {
                LOG.error(MessageFormat.format(
                        "cannot extract the entry {0} from the {1}. because it is a directory", entry.getName(),
                        zipFile.getAbsolutePath()));
                continue;
            }

            // extract the file to the provided destination
            // we have to watch out for a unique name of the file to be extracted:
            // it can happen, that several at the same time incoming messages have a file with the same name
            File extracted = new File(FileUtils.getFilename(toDir, entry.getName()));
            if (!extracted.getParentFile().mkdirs()) {
                LOG.debug("cannot make all the necessary directories for the file "
                        + extracted.getAbsolutePath() + " or " + "the path is already created ");
            }

            try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(extracted),
                    BUFFER_SIZE)) {
                byte[] data = new byte[BUFFER_SIZE];
                int count;
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }

                files.add(extracted);
            }
        }

    }

    return files;
}

From source file:com.worldline.easycukes.commons.helpers.FileHelper.java

/**
 * Extracts the content of a zip folder in a specified directory
 *
 * @param from a {@link String} representation of the URL containing the zip
 *             file to be unzipped/*from ww w .ja v a 2s . c  o m*/
 * @param to   the path on which the content should be extracted
 * @throws IOException if anything's going wrong while unzipping the content of the
 *                     provided zip folder
 */
public static void unzip(@NonNull String from, @NonNull String to, boolean isRemote) throws IOException {
    @Cleanup
    ZipInputStream zip = null;
    if (isRemote)
        zip = new ZipInputStream(new FileInputStream(from));
    else
        zip = new ZipInputStream(FileHelper.class.getResourceAsStream(from));
    log.debug("Extracting zip from: " + from + " to: " + to);
    // Extract without a container directory if exists
    ZipEntry entry = zip.getNextEntry();
    String rootDir = "/";
    if (entry != null)
        if (entry.isDirectory())
            rootDir = entry.getName();
        else {
            final String filePath = to + entry.getName();
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        }
    zip.closeEntry();
    entry = zip.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String entryName = entry.getName();
        if (entryName.startsWith(rootDir))
            entryName = entryName.replaceFirst(rootDir, "");
        final String filePath = to + "/" + entryName;
        if (!entry.isDirectory())
            // if the entry is a file, extracts it
            try {
                extractFile(zip, filePath);
            } catch (final FileNotFoundException fnfe) {
                log.warn(fnfe.getMessage(), fnfe);
            }
        else {
            // if the entry is a directory, make the directory
            final File dir = new File(filePath);
            dir.mkdir();
        }
        zip.closeEntry();
        entry = zip.getNextEntry();
    }
    // delete the zip file if recovered from URL
    if (isRemote)
        new File(from).delete();
}

From source file:net.minecrell.quartz.launch.mappings.MappingsLoader.java

public static Mappings load(Logger logger) throws IOException {
    URI source;//from  ww  w  .j a va 2 s  .  co m
    try {
        source = requireNonNull(Mapping.class.getProtectionDomain().getCodeSource(),
                "Unable to find class source").getLocation().toURI();
    } catch (URISyntaxException e) {
        throw new IOException("Failed to find class source", e);
    }

    Path location = Paths.get(source);
    logger.debug("Mappings location: {}", location);

    List<ClassNode> mappingClasses = new ArrayList<>();

    // Load the classes from the source
    if (Files.isDirectory(location)) {
        // We're probably in development environment or something similar
        // Search for the class files
        Files.walkFileTree(location.resolve(PACKAGE), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    try (InputStream in = Files.newInputStream(file)) {
                        ClassNode classNode = MappingsParser.loadClassStructure(in);
                        mappingClasses.add(classNode);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        // Go through the JAR file
        try (ZipFile zip = new ZipFile(location.toFile())) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String name = StringUtils.removeStart(entry.getName(), MAPPINGS_DIR);
                if (entry.isDirectory() || !name.endsWith(".class") || !name.startsWith(PACKAGE_PREFIX)) {
                    continue;
                }

                // Ok, we found something
                try (InputStream in = zip.getInputStream(entry)) {
                    ClassNode classNode = MappingsParser.loadClassStructure(in);
                    mappingClasses.add(classNode);
                }
            }
        }
    }

    return new Mappings(mappingClasses);
}

From source file:org.cloudfoundry.client.lib.SampleProjects.java

private static void unpackZip(ZipFile zipFile, File unpackDir) throws IOException {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File destination = new File(unpackDir.getAbsolutePath() + "/" + entry.getName());
        if (entry.isDirectory()) {
            destination.mkdirs();/* ww  w.  java 2  s  .  c om*/
        } else {
            destination.getParentFile().mkdirs();
            FileCopyUtils.copy(zipFile.getInputStream(entry), new FileOutputStream(destination));
        }
        if (entry.getTime() != -1) {
            destination.setLastModified(entry.getTime());
        }
    }
}

From source file:org.apache.kylin.common.util.ZipFileUtils.java

public static void decompressZipfileToDirectory(String zipFileName, File outputFolder) throws IOException {
    ZipInputStream zipInputStream = null;
    try {// ww w.  j a v  a2s .  c o  m
        zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));
        ZipEntry zipEntry = null;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            logger.info("decompressing " + zipEntry.getName() + " is directory:" + zipEntry.isDirectory()
                    + " available: " + zipInputStream.available());

            File temp = new File(outputFolder, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                temp.mkdirs();
            } else {
                temp.getParentFile().mkdirs();
                temp.createNewFile();
                temp.setLastModified(zipEntry.getTime());
                FileOutputStream outputStream = new FileOutputStream(temp);
                try {
                    IOUtils.copy(zipInputStream, outputStream);
                } finally {
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:net.sf.jabref.importer.ZipFileChooser.java

/**
 * Entries that can be selected with this dialog.
 *
 * @param zipFile  Zip-File/* ww w. j a  va2s .  com*/
 * @return  entries that can be selected
 */
private static ZipEntry[] getSelectableZipEntries(ZipFile zipFile) {
    List<ZipEntry> entries = new ArrayList<>();
    Enumeration<? extends ZipEntry> e = zipFile.entries();
    for (ZipEntry entry : Collections.list(e)) {
        if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
            entries.add(entry);
        }
    }
    return entries.toArray(new ZipEntry[entries.size()]);
}

From source file:org.ancoron.osgi.test.glassfish.GlassfishHelper.java

public static void unzip(String zipFile, String targetPath) throws IOException {
    log.log(Level.INFO, "Extracting {0} ...", zipFile);
    log.log(Level.INFO, "...target directory: {0}", targetPath);
    File path = new File(targetPath);
    path.delete();//from  ww  w.  j a va 2  s .  c  om
    path.mkdirs();

    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            File f = new File(targetPath + "/" + entry.getName());
            f.mkdirs();
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER];

        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(targetPath + "/" + entry.getName());
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:de.xwic.appkit.core.util.ZipUtil.java

/**
 * Unzips the files from the zipped file into the destination folder.
 * /*  w w w .  j ava 2s.c o m*/
 * @param zippedFile
 *            the files array
 * @param destinationFolder
 *            the folder in which the zip archive will be unzipped
 * @return the file array which consists into the files which were zipped in
 *         the zippedFile
 * @throws IOException
 */
public static File[] unzip(File zippedFile, String destinationFolder) throws IOException {

    ZipFile zipFile = null;
    List<File> files = new ArrayList<File>();

    try {

        zipFile = new ZipFile(zippedFile);
        Enumeration<?> entries = zipFile.entries();

        while (entries.hasMoreElements()) {

            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (!entry.isDirectory()) {

                String filePath = destinationFolder + System.getProperty("file.separator") + entry.getName();
                FileOutputStream stream = new FileOutputStream(filePath);

                InputStream is = zipFile.getInputStream(entry);

                log.info("Unzipping " + entry.getName());

                int n = 0;
                while ((n = is.read(BUFFER)) > 0) {
                    stream.write(BUFFER, 0, n);
                }

                is.close();
                stream.close();

                files.add(new File(filePath));

            }

        }

        zipFile.close();
    } catch (IOException e) {

        log.error("Error: " + e.getMessage(), e);
        throw e;

    } finally {

        try {

            if (null != zipFile) {
                zipFile.close();
            }

        } catch (IOException e) {
            log.error("Error: " + e.getMessage(), e);
            throw e;
        }

    }

    File[] array = files.toArray(new File[files.size()]);
    return array;
}