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:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Inflate the provided {@link ZipFile} in the provided output directory.
 * //from w ww.  ja  v a 2 s.  c  o  m
 * @param archive
 *            the {@link ZipFile} to inflate.
 * @param outputDirectory
 *            the directory where to inflate the archive.
 * @throws IOException
 *             in case something bad happens.
 * @throws FileNotFoundException
 *             in case something bad happens.
 */
public static void inflate(ZipFile archive, File outputDirectory, String fileName)
        throws IOException, FileNotFoundException {

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

            if (!entry.isDirectory()) {
                final String name = entry.getName();
                final String ext = FilenameUtils.getExtension(name);
                final InputStream in = new BufferedInputStream(archive.getInputStream(entry));
                final File outFile = new File(outputDirectory,
                        fileName != null ? new StringBuilder(fileName).append(".").append(ext).toString()
                                : name);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));

                IOUtils.copyStream(in, out, true, true);
            }
        }
    } finally {
        try {
            archive.close();
        } catch (Throwable e) {
            if (LOGGER.isTraceEnabled())
                LOGGER.error("unable to close archive.\nMessage is: " + e.getMessage(), e);
        }
    }

}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Inflate a pale file to a given working directory.
 * //from  www  . j  a  v a  2s  . c  o m
 * @param paleFile .pale file to inflate.
 * @param workingDir Path to extract to.
 * @return Path of the location the file was extracted to.
 * @throws FileNotFoundException
 * @throws IOException
 */
public static File decompress(File paleFile, File workingDir) throws FileNotFoundException, IOException {
    ZipFile archive = new ZipFile(paleFile);

    try {
        // Iterate over elements in zip file and extract them to working
        // directory.
        Enumeration<? extends ZipEntry> entries = archive.entries();
        while (entries.hasMoreElements()) {
            ZipEntry ze = entries.nextElement();
            File newFile = new File(workingDir, ze.getName());

            if (ze.isDirectory()) {
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                continue;
            }

            if (!newFile.getParentFile().exists()) {
                // Dir tree missing for some reason so create it.
                newFile.getParentFile().mkdirs();
            }

            InputStream in = archive.getInputStream(ze);
            OutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));

            try {
                copy(in, out);
            } finally {
                in.close();
                out.close();
            }
        }
    } finally {
        archive.close();
    }

    return workingDir;
}

From source file:org.atomserver.utils.io.JarUtils.java

/**
 * Copies an entire folder out of a jar to a physical location (i.e. to a directory).
 * @param cl The ClassLoader to use when pulling resources from the Jar
 * @param jar  The jar opened as a File//www.  j ava 2 s.c  om
 * @param folderName  The folder name in the jar (e.g. test-resources/var)
 * @param destDir The root directory to copy into (will be created if req'd)
 * @throws IOException
 */
static public void copyJarFolder(ClassLoader cl, File jar, String folderName, File destDir) throws IOException {

    log.debug("jar= " + jar + " destDir= " + destDir + " folderName= " + folderName);

    FileUtils.forceMkdir(destDir);

    ZipFile zipfile = new ZipFile(jar);

    Enumeration entries = zipfile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        log.trace("examining ENTRY = " + entry.getName());

        if (entry.getName().contains(folderName)) {
            File fileDest = new File(destDir, entry.getName());
            if (!fileDest.exists()) {
                if (entry.isDirectory()) {
                    log.trace("Creating Directory :: " + fileDest);
                    FileUtils.forceMkdir(fileDest);
                } else {
                    copyFromJar(cl, entry.getName(), fileDest);
                }
            } else {
                log.trace("file (" + fileDest + ") already exists");
            }

        }
    }
}

From source file:Main.java

public static void unzip(String strZipFile) {

    try {//ww w .j  a  v  a2s . c o m
        /*
         * STEP 1 : Create directory with the name of the zip file
         * 
         * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries
         */
        File fSourceZip = new File(strZipFile);
        String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
        File temp = new File(zipPath);
        temp.mkdir();
        System.out.println(zipPath + " created");

        /*
         * STEP 2 : Extract entries while creating required sub-directories
         */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());

            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();

            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                // System.out.println("Extracting " + destinationFilePath);

                /*
                 * Get the InputStream for current entry of the zip file using
                 * 
                 * InputStream getInputStream(Entry entry) method.
                 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

                int b;
                byte buffer[] = new byte[1024];

                /*
                 * read the current entry from the zip file, extract it and write the extracted file.
                 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }

                // flush the output stream and close it.
                bos.flush();
                bos.close();

                // close the input stream.
                bis.close();
            }

        }
        zipFile.close();
    } catch (IOException ioe) {
        System.out.println("IOError :" + ioe);
    }

}

From source file:net.minecraftforge.fml.common.asm.transformers.AccessTransformer.java

private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;//from w  w w  . j a  v  a  2  s  .com
    ZipOutputStream outJar = null;

    try {
        try {
            inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        ZipEntry entry;
        while ((entry = inJar.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                outJar.putNextEntry(entry);
                continue;
            }

            byte[] data = new byte[4096];
            ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();

            int len;
            do {
                len = inJar.read(data);
                if (len > 0) {
                    entryBuffer.write(data, 0, len);
                }
            } while (len != -1);

            byte[] entryData = entryBuffer.toByteArray();

            String entryName = entry.getName();

            if (entryName.endsWith(".class") && !entryName.startsWith(".")) {
                ClassNode cls = new ClassNode();
                ClassReader rdr = new ClassReader(entryData);
                rdr.accept(cls, 0);
                String name = cls.name.replace('/', '.').replace('\\', '.');

                for (AccessTransformer trans : transformers) {
                    entryData = trans.transform(name, name, entryData);
                }
            }

            ZipEntry newEntry = new ZipEntry(entryName);
            outJar.putNextEntry(newEntry);
            outJar.write(entryData);
        }
    } finally {
        IOUtils.closeQuietly(outJar);
        IOUtils.closeQuietly(inJar);
    }
}

From source file:com.t3.persistence.FileUtil.java

public static void unzip(ZipInputStream in, File destDir) throws IOException {
    if (in == null)
        throw new IOException("input stream cannot be null");

    // Prepare destination
    destDir.mkdirs();//  w ww . ja v  a 2s .  co m
    String absDestDir = destDir.getAbsolutePath() + File.separator;

    // Pull out the files
    ZipEntry entry = null;

    while ((entry = in.getNextEntry()) != null) {
        if (entry.isDirectory())
            continue;

        // Prepare file destination
        String path = absDestDir + entry.getName();
        File file = new File(path);
        file.getParentFile().mkdirs();

        try (OutputStream out = new FileOutputStream(file)) {
            IOUtils.copy(in, out);
        }
        in.closeEntry();
    }
}

From source file:cn.edu.zju.acm.onlinejudge.util.ProblemManager.java

public static ProblemPackage importProblem(InputStream in, ActionMessages messages) {

    Map<String, byte[]> files = new HashMap<String, byte[]>();
    ZipInputStream zis = null;/*w  w  w  . ja v a2  s . c  om*/
    try {

        zis = new ZipInputStream(new BufferedInputStream(in));
        // zis = new ZipInputStream(new BufferedInputStream(new FileInputStream("d:/100.zip")));
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {

                // TODO the file may be too big. > 100M
                /*
                 * byte data[] = new byte[(int) entry.getSize()]; int l = 0; while (l < data.length) { int ll =
                 * zis.read(data, l, data.length - l); if (ll < 0) { break; } l += ll; }
                 */
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                CopyUtils.copy(zis, buf);
                files.put(entry.getName(), buf.toByteArray());

            }
            entry = zis.getNextEntry();
        }

    } catch (IOException ioe) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.invalidzip"));
        return null;
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
    /*
     * files.clear(); files.put("problems.csv", "3,a\n2,b,true,1,2,3,4,a,b,c\n1,c".getBytes());
     * files.put("1\\checker", "checker".getBytes()); files.put("1\\input", "input".getBytes());
     * files.put("1\\output", "output".getBytes()); files.put("3\\checker", "checker3".getBytes());
     * files.put("3\\input", "input3".getBytes()); files.put("3\\output", "output3".getBytes());
     * files.put("images\\1.jpg", "1".getBytes()); files.put("images\\2\\2.jpg", "2".getBytes());
     */
    if (!files.containsKey(ProblemManager.PROBLEM_CSV_FILE)) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.missingproblemscsv"));
        return null;
    }
    ProblemPackage problemPackage = ProblemManager.parse(files, messages);
    if (messages.size() > 0) {
        return null;
    }
    return problemPackage;
}

From source file:Main.java

/**
 * //from  w w w  .  j a  va  2s  . c  o m
 * @param zipFile
 *            zip file
 * @param folderName
 *            folder to load
 * @return list of entry in the folder
 * @throws ZipException
 * @throws IOException
 */
public static List<ZipEntry> loadFiles(File zipFile, String folderName) throws ZipException, IOException {
    Log.d("loadFiles", folderName);
    long start = System.currentTimeMillis();
    FileInputStream fis = new FileInputStream(zipFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis);

    ZipEntry zipEntry = null;
    List<ZipEntry> list = new LinkedList<ZipEntry>();
    String folderLowerCase = folderName.toLowerCase();
    int counter = 0;
    while ((zipEntry = zis.getNextEntry()) != null) {
        counter++;
        String zipEntryName = zipEntry.getName();
        Log.d("loadFiles.zipEntry.getName()", zipEntryName);
        if (zipEntryName.toLowerCase().startsWith(folderLowerCase) && !zipEntry.isDirectory()) {
            list.add(zipEntry);
        }
    }
    Log.d("Loaded 1", counter + " files, took: " + (System.currentTimeMillis() - start) + " milliseconds.");
    zis.close();
    bis.close();
    fis.close();
    return list;
}

From source file:net.sf.jasperreports.samples.wizards.SampleNewWizard.java

public static void unpackArchive(File theFile, File targetDir, IProgressMonitor monitor, Set<String> cpaths,
        Set<String> lpaths) {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = null;/* w w  w  . j  a  va 2  s .com*/
    try {
        zis = new ZipInputStream(new FileInputStream(theFile));

        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            File file = new File(targetDir, File.separator + ze.getName());

            new File(file.getParent()).mkdirs();
            String fname = file.getName();
            if (ze.isDirectory()) {
                if (fname.equals("src"))
                    cpaths.add(ze.getName());
            } else {
                FileOutputStream fos = new FileOutputStream(file);
                int len;
                while ((len = zis.read(buffer)) > 0)
                    fos.write(buffer, 0, len);

                fos.close();
            }
            if (file.getParentFile().getName().equals("lib")
                    && (fname.endsWith(".jar") || fname.endsWith(".zip")))
                lpaths.add(ze.getName());
            if (monitor.isCanceled()) {
                zis.close();
                return;
            }
            ze = zis.getNextEntry();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            zis.closeEntry();
            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.freedomotic.util.Unzip.java

/**
 *
 * @param zipFile//from  w  w w . java 2  s. c o m
 * @throws ZipException
 * @throws IOException
 */
public static void unzip(String zipFile) throws IOException {

    if (StringUtils.isEmpty(zipFile)) {
        LOG.error("File path not provided, no unzipping performed");
        return;
    }

    File file = new File(zipFile);

    if (!file.exists()) {
        LOG.error("File not existing, no unzipping performed");
        return;
    }

    try (ZipFile zip = new ZipFile(file);) {
        String newPath = zipFile.substring(0, zipFile.length() - 4);
        //simulates the unzip here feature
        newPath = newPath.substring(0, newPath.lastIndexOf(File.separator));

        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            File destinationParent = destFile.getParentFile();

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

            if (!entry.isDirectory()) {
                try (BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                        FileOutputStream fos = new FileOutputStream(destFile);
                        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);) {

                    int currentByte;

                    // establish buffer for writing file
                    byte[] data = new byte[BUFFER];

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (IOException ex) {
                    LOG.error(Freedomotic.getStackTraceInfo(ex));
                }
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to open
                unzip(destFile.getAbsolutePath());
            }
        }
    }
}