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:CrossRef.java

/** For each Zip file, for each entry, xref it */
public void processOneZip(String fileName) throws IOException {
    List entries = new ArrayList();
    ZipFile zipFile = null;//w  w  w  .  j av a  2  s .c o m

    try {
        zipFile = new ZipFile(new File(fileName));
    } catch (ZipException zz) {
        throw new FileNotFoundException(zz.toString() + fileName);
    }
    Enumeration all = zipFile.entries();

    // Put the entries into the List for sorting...
    while (all.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) all.nextElement();
        entries.add(zipEntry);
    }

    // Sort the entries (by class name)
    // Collections.sort(entries);

    // Process all the entries in this zip.
    Iterator it = entries.iterator();
    while (it.hasNext()) {
        ZipEntry zipEntry = (ZipEntry) it.next();
        String zipName = zipEntry.getName();

        // Ignore package/directory, other odd-ball stuff.
        if (zipEntry.isDirectory()) {
            continue;
        }

        // Ignore META-INF stuff
        if (zipName.startsWith("META-INF/")) {
            continue;
        }

        // Ignore images, HTML, whatever else we find.
        if (!zipName.endsWith(".class")) {
            continue;
        }

        // If doing CLASSPATH, Ignore com.* which are "internal API".
        //    if (doingStandardClasses && !zipName.startsWith("java")){
        //       continue;
        //    }

        // Convert the zip file entry name, like
        //   java/lang/Math.class
        // to a class name like
        //   java.lang.Math
        String className = zipName.replace('/', '.').substring(0, zipName.length() - 6); // 6 for ".class"

        // Now get the Class object for it.
        Class c = null;
        try {
            c = Class.forName(className);
        } catch (ClassNotFoundException ex) {
            System.err.println("Error: " + ex);
        }

        // Hand it off to the subclass...
        doClass(c);
    }
}

From source file:net.pms.configuration.DownloadPlugins.java

private void unzip(File f, String dir) {
    // Zip file with loads of goodies
    // Unzip it/* ww  w.j  a va  2 s . c  om*/
    ZipInputStream zis;
    try {
        zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File dst = new File(dir + File.separator + entry.getName());
            if (entry.isDirectory()) {
                dst.mkdirs();
                continue;
            }
            int count;
            byte data[] = new byte[4096];
            FileOutputStream fos = new FileOutputStream(dst);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, 4096)) {
                while ((count = zis.read(data, 0, 4096)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
            }
            if (dst.getAbsolutePath().endsWith(".jar")) {
                jars.add(dst.toURI().toURL());
            }
        }
        zis.close();
    } catch (Exception e) {
        LOGGER.info("unzip error " + e);
    }
    f.delete();
}

From source file:com.polyvi.xface.extension.zip.XZipExt.java

/**
 * ??zip?// w  w w.  j  ava 2  s .  c o  m
 *
 * @param dstFileUri
 *            
 * @param is
 *            ?zip?
 * @return ??
 * @throws IOException
 * @throws FileNotFoundException
 * @throws IllegalArgumentException
 */
private void unzipFileFromStream(Uri dstFileUri, InputStream is)
        throws IOException, FileNotFoundException, IllegalArgumentException {
    if (null == dstFileUri || null == is) {
        XLog.e(CLASS_NAME, "Method unzipFileFromStream: params is null");
        throw new IllegalArgumentException();
    }
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry = null;
    Uri unZipUri = null;
    while (null != (entry = zis.getNextEntry())) {
        File unZipFile = new File(dstFileUri.getPath() + File.separator + entry.getName());
        unZipUri = Uri.fromFile(unZipFile);
        if (entry.isDirectory()) {
            if (!unZipFile.exists()) {
                unZipFile.mkdirs();
            }
        } else {
            // ???
            prepareForZipDir(unZipUri);
            OutputStream fos = mResourceApi.openOutputStream(unZipUri);
            int readLen = 0;
            byte buffer[] = new byte[XConstant.BUFFER_LEN];
            while (-1 != (readLen = zis.read(buffer))) {
                fos.write(buffer, 0, readLen);
            }
            fos.close();
        }
    }
    zis.close();
    is.close();
}

From source file:forge.CardStorageReader.java

/**
 * Starts reading cards into memory until the given card is found.
 *
 * After that, we save our place in the list of cards (on disk) in case we
 * need to load more./*from w w  w . j  av  a  2 s.c o m*/
 *
 * @return the Card or null if it was not found.
 */
public final Iterable<CardRules> loadCards() {

    final Localizer localizer = Localizer.getInstance();

    progressObserver.setOperationName(localizer.getMessage("splash.loading.examining-cards"), true);

    // Iterate through txt files or zip archive.
    // Report relevant numbers to progress monitor model.

    final Set<CardRules> result = new TreeSet<>(new Comparator<CardRules>() {
        @Override
        public int compare(final CardRules o1, final CardRules o2) {
            return String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName());
        }
    });

    final List<File> allFiles = collectCardFiles(new ArrayList<File>(), this.cardsfolder);
    if (!allFiles.isEmpty()) {
        int fileParts = zip == null ? NUMBER_OF_PARTS : 1 + NUMBER_OF_PARTS / 3;
        if (allFiles.size() < fileParts * 100) {
            fileParts = allFiles.size() / 100; // to avoid creation of many threads for a dozen of files
        }
        final CountDownLatch cdlFiles = new CountDownLatch(fileParts);
        final List<Callable<List<CardRules>>> taskFiles = makeTaskListForFiles(allFiles, cdlFiles);
        progressObserver.setOperationName(localizer.getMessage("splash.loading.cards-folders"), true);
        progressObserver.report(0, taskFiles.size());
        final StopWatch sw = new StopWatch();
        sw.start();
        executeLoadTask(result, taskFiles, cdlFiles);
        sw.stop();
        final long timeOnParse = sw.getTime();
        System.out.printf("Read cards: %s files in %d ms (%d parts) %s%n", allFiles.size(), timeOnParse,
                taskFiles.size(), useThreadPool ? "using thread pool" : "in same thread");
    }

    if (this.zip != null) {
        final CountDownLatch cdlZip = new CountDownLatch(NUMBER_OF_PARTS);
        List<Callable<List<CardRules>>> taskZip;

        ZipEntry entry;
        final List<ZipEntry> entries = new ArrayList<>();
        // zipEnum was initialized in the constructor.
        final Enumeration<? extends ZipEntry> zipEnum = this.zip.entries();
        while (zipEnum.hasMoreElements()) {
            entry = zipEnum.nextElement();
            if (entry.isDirectory() || !entry.getName().endsWith(CardStorageReader.CARD_FILE_DOT_EXTENSION)) {
                continue;
            }
            entries.add(entry);
        }

        taskZip = makeTaskListForZip(entries, cdlZip);
        progressObserver.setOperationName(localizer.getMessage("splash.loading.cards-archive"), true);
        progressObserver.report(0, taskZip.size());
        final StopWatch sw = new StopWatch();
        sw.start();
        executeLoadTask(result, taskZip, cdlZip);
        sw.stop();
        final long timeOnParse = sw.getTime();
        System.out.printf("Read cards: %s archived files in %d ms (%d parts) %s%n", this.zip.size(),
                timeOnParse, taskZip.size(), useThreadPool ? "using thread pool" : "in same thread");
    }

    return result;
}

From source file:com.denel.facepatrol.MainActivity.java

private void downloadunzip() throws IOException {
    // for now the file is from assets but will be downloaded later
    String PATH = getApplicationContext().getDir("pictures", 0).getAbsolutePath() + "/";
    InputStream is = getApplicationContext().getAssets().open("ContactsPics.zip");

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    try {//from  w  w  w  .  jav  a2 s  .  c o m
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        while ((ze = zis.getNextEntry()) != null) {

            if (ze.isDirectory()) {
                _dirchecker((ze.getName()));
            } else {
                FileOutputStream baos = new FileOutputStream(PATH + ze.getName());
                BufferedInputStream in = new BufferedInputStream(zis);
                BufferedOutputStream out = new BufferedOutputStream(baos);

                int count;
                while ((count = in.read(buffer)) > 0) {
                    out.write(buffer, 0, count);
                }
                zis.closeEntry();
                out.close();
            }

        }
    } finally {
        zis.close();
    }
}

From source file:com.disney.opa.util.AttachmentUtils.java

/**
 * This method is to extract the zip files and creates attachment objects.
 * // w w w  .  ja va  2 s.c o m
 * @param attachment
 * @param fileNames
 * @param fileLabels
 * @param errors
 * @return list of attachments from the zip file
 */
public List<Attachment> processZipFile(Attachment attachment, List<String> fileNames, List<String> fileLabels,
        List<String> errors) {
    ZipFile zipFile = null;
    List<Attachment> attachments = new ArrayList<Attachment>();
    try {
        String zipFilePath = getOriginalAttachmentsPath(attachment.getProductID()) + File.separator
                + attachment.getFilename();
        zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String fileName = entry.getName();
            File destinationFile = new File(
                    getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + fileName);
            uploadFile(zipFile.getInputStream(entry), destinationFile);
            String label = createUniqueFileLabel(fileName, null, fileLabels);
            Attachment fileAttachment = getAttachment(fileName, label, attachment.getProductID(),
                    attachment.getProductStateID(), attachment.getUserID());
            if (fileAttachment.getFileSize() == 0L) {
                errors.add("File not found, file name: " + fileName + ", in zip file: "
                        + attachment.getFilename());
            } else {
                attachments.add(fileAttachment);
            }
        }
    } catch (Exception e) {
        errors.add(
                "Error while processing zip: " + attachment.getFilename() + ", title: " + attachment.getName());
        log.error("Error while processing zip.", e);
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (IOException e) {
        }
    }
    return attachments;
}

From source file:com.ichi2.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Timber.e("Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*w  ww .j  a  v  a 2s. c o m*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    Timber.i("uncompress %s", name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Timber.e(e, "Utils.unzipFiles: Error while unzipping archive.");
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing output stream.");
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing zip input stream.");
        }
    }
    return true;
}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

private InputStream getInputStream(ZipFile zipFile, String entryFileName) throws Exception {
    ZipEntry topLevelFolder = null;
    ZipEntry specificEntry = null;
    InputStream ipStream = null;//ww w.ja v  a2s  .c  om

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        topLevelFolder = entries.nextElement();
        if (topLevelFolder.isDirectory()) {
            break;
        }
    }

    if (topLevelFolder != null) {
        String lookupFile = topLevelFolder + entryFileName;
        specificEntry = zipFile.getEntry(lookupFile);
    }

    if (specificEntry != null) {
        ipStream = zipFile.getInputStream(specificEntry);
    }

    return ipStream;
}

From source file:me.hqm.plugindev.wget.WGCommand.java

/**
 * Download a URL (jar or zip) to a file
 *
 * @param url Valid URL/*from  w  w  w . j  a  v a2s  . c  o m*/
 * @return Success or failure
 */
private boolean download(URL url) {
    // The plugin folder path
    String path = plugin.getDataFolder().getParentFile().getPath();

    // Wrap everything in a try/catch
    try {
        // Get the filename from the url
        String fileName = fileName(url);

        // Create a new input stream and output file
        InputStream in = url.openStream();
        File outFile = new File(path + "/" + fileName);

        // If the file already exists, delete it
        if (outFile.exists()) {
            outFile.delete();
        }

        // Create the output stream and download the file
        FileOutputStream out = new FileOutputStream(outFile);
        IOUtils.copy(in, out);

        // Close the streams
        in.close();
        out.close();

        // If downloaded file is a zip file...
        if (fileName.endsWith(".zip")) {
            // Declare a new input stream outside of a try/catch
            ZipInputStream zis = null;
            try {
                // Define the input stream
                zis = new ZipInputStream(new FileInputStream(outFile));

                // Decalre a zip entry for the while loop
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    // Make a new file object for the entry
                    File entryFile = new File(path, entry.getName());

                    // If it is a directory and doesn't already exist, create the new directory
                    if (entry.isDirectory()) {
                        if (!entryFile.exists()) {
                            entryFile.mkdirs();
                        }
                    } else {
                        // Make sure all folders exist
                        if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) {
                            entryFile.getParentFile().mkdirs();
                        }

                        // Create file on disk
                        if (!entryFile.exists() && !entryFile.createNewFile()) {
                            // Access denied, let the console know
                            throw new AccessDeniedException(entryFile.getPath());
                        }

                        // Write data to file from zip.
                        OutputStream os = null;
                        try {
                            os = new FileOutputStream(entryFile);
                            IOUtils.copy(zis, os);
                        } finally {
                            // Silently close the output stream
                            IOUtils.closeQuietly(os);
                        }
                    }
                }
            } finally {
                // Always close streams
                IOUtils.closeQuietly(zis);
            }

            // Delete the zip file
            outFile.delete();
        }

        // Return success
        return true;
    } catch (NullPointerException | IOException oops) {
        getLogger().severe("---------- WGET BEGIN -----------");
        getLogger().severe("An error occurred during a file download/extraction:");
        oops.printStackTrace();
        getLogger().severe("----------- WGET END ------------");
    }

    // The download failed, report failure
    return false;
}

From source file:fr.certu.chouette.gui.command.ImportCommand.java

/**
 * @param session//from ww  w  .j a v  a 2  s  . c  o  m
 * @param save
 * @param savedIds
 * @param manager
 * @param importTask
 * @param format
 * @param inputFile
 * @param suffixes
 * @param values
 * @param importHolder
 * @param validationHolder
 * @throws ChouetteException
 */
private int importZipEntries(EntityManager session, boolean save, List<Long> savedIds,
        INeptuneManager<NeptuneIdentifiedObject> manager, ImportTask importTask, String format,
        String inputFile, List<String> suffixes, List<ParameterValue> values, ReportHolder importHolder,
        ReportHolder validationHolder) throws ChouetteException {
    SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
    values.add(inputFileParam);

    ReportHolder zipHolder = new ReportHolder();
    if (format.equalsIgnoreCase("neptune")) {
        SharedImportedData sharedData = new SharedImportedData();
        UnsharedImportedData unsharedData = new UnsharedImportedData();
        SimpleParameterValue sharedDataParam = new SimpleParameterValue("sharedImportedData");
        sharedDataParam.setObjectValue(sharedData);
        values.add(sharedDataParam);
        SimpleParameterValue unsharedDataParam = new SimpleParameterValue("unsharedImportedData");
        unsharedDataParam.setObjectValue(unsharedData);
        values.add(unsharedDataParam);
    }

    // unzip files , import and save contents
    ZipFile zip = null;
    File temp = null;
    File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importTask.getId());
    if (!tempRep.exists())
        tempRep.mkdirs();
    File zipFile = new File(inputFile);
    ReportItem zipReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_FILE, Report.STATE.OK,
            zipFile.getName());
    try {
        Charset encoding = FileTool.getZipCharset(inputFile);
        if (encoding == null) {
            ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR,
                    Report.STATE.ERROR, "unknown encoding");
            zipReportItem.addItem(fileErrorItem);
            importHolder.getReport().addItem(zipReportItem);
            saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
            return 1;
        }
        zip = new ZipFile(inputFile, encoding);
        zipHolder.setReport(zipReportItem);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                File dir = new File(tempRep, entry.getName());
                dir.mkdirs();
                continue;
            }
            if (!FilenameUtils.isExtension(entry.getName().toLowerCase(), suffixes)) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                        Report.STATE.OK, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.info("entry " + entry.getName() + " ignored, unknown extension");
                continue;
            }
            InputStream stream = null;
            try {
                stream = zip.getInputStream(entry);
            } catch (IOException e) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR,
                        Report.STATE.WARNING, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.error("entry " + entry.getName() + " cannot read", e);
                continue;
            }
            byte[] bytes = new byte[4096];
            int len = stream.read(bytes);
            temp = new File(tempRep.getAbsolutePath() + "/" + entry.getName());
            FileOutputStream fos = new FileOutputStream(temp);
            while (len > 0) {
                fos.write(bytes, 0, len);
                len = stream.read(bytes);
            }
            fos.close();

            // import
            log.info("import file " + entry.getName());
            inputFileParam.setFilepathValue(temp.getAbsolutePath());
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, zipHolder,
                    validationHolder);
            if (beans != null && !beans.isEmpty()) {
                // save
                if (save) {
                    saveBeans(manager, beans, savedIds, importHolder.getReport());
                } else {
                    for (NeptuneIdentifiedObject bean : beans) {
                        GuiReportItem item = new GuiReportItem(GuiReportItem.KEY.NO_SAVE, Report.STATE.OK,
                                bean.getName());
                        importHolder.getReport().addItem(item);
                    }

                }
            }
            temp.delete();
        }
        try {
            zip.close();
        } catch (IOException e) {
            log.info("cannot close zip file");
        }
        importHolder.getReport().addItem(zipReportItem);
    } catch (IOException e) {
        log.error("IO error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } catch (IllegalArgumentException e) {
        log.error("Format error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } finally {
        try {
            FileUtils.deleteDirectory(tempRep);
        } catch (IOException e) {
            log.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
        }
    }
    return 0;
}