Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public BackupResourceIterable getBackupResources(Backup backup) {
    final File archiveFile = new File(backupDir, String.format(ARCHIVE_KEY_NAME_FORMAT, backup.getKey()));
    if (!(archiveFile.isFile() && archiveFile.canRead())) {
        log.warn("No backup archive exists for key [{}]", backup.getKey());
        Collection<BackupResource> col = Collections.emptyList();
        return new CollectionBackupResourceIterable(col);
    }/*from w ww  .j a v a 2  s  .  c om*/
    try {
        final ZipFile zf = new ZipFile(archiveFile);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        List<BackupResource> result = new ArrayList<BackupResource>(20);
        while (entries.hasMoreElements()) {
            result.add(new ZipEntryBackupResource(zf, entries.nextElement()));
        }
        return new CollectionBackupResourceIterable(result) {

            @Override
            public void close() throws IOException {
                zf.close();
            }

        };
    } catch (IOException e) {
        log.error("Error extracting backup archive entries: {}", e.getMessage());
    }
    Collection<BackupResource> col = Collections.emptyList();
    return new CollectionBackupResourceIterable(col);
}

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

/**
 * This method is to extract the zip files and creates attachment objects.
 * //from  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.impetus.ankush.common.utils.FileNameUtils.java

/**
 * Gets the extracted directory name.//from www.j  a v a  2 s  .co m
 * 
 * @param archiveFile
 *            the archive file
 * @return Directory name after extraction of archiveFile
 */
public static String getExtractedDirectoryName(String archiveFile) {
    String path = null;
    ONSFileType fileType = getFileType(archiveFile);

    if (fileType == ONSFileType.TAR_GZ || fileType == ONSFileType.GZ) {
        try {
            GZIPInputStream gzipInputStream = null;
            gzipInputStream = new GZIPInputStream(new FileInputStream(archiveFile));
            TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipInputStream);

            return tarInput.getNextTarEntry().getName();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    } else if (fileType == ONSFileType.ZIP || fileType == ONSFileType.BIN) {
        ZipFile zf;
        try {
            zf = new ZipFile(archiveFile);
            Enumeration<? extends ZipEntry> entries = zf.entries();

            return entries.nextElement().getName();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    return path;
}

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

/**
 * unzip a file in the same directory as the zipped file
 * /*from w  w  w.j av  a2 s  . 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:ClassFinder.java

private static void findClassesInOnePath(String strPath, Set<String> listClasses) throws IOException {
    File file = new File(strPath);
    if (file.isDirectory()) {
        findClassesInPathsDir(strPath, file, listClasses);
    } else if (file.exists()) {
        ZipFile zipFile = new ZipFile(file);
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            String strEntry = entries.nextElement().toString();
            if (strEntry.endsWith(DOT_CLASS)) {
                listClasses.add(fixClassName(strEntry));
            }/*w  ww . j  a va  2s.  c  o m*/
        }
        zipFile.close();
    }
}

From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*  w  ww  . j  a v  a  2  s .c om*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            if (cache != null) {
                cache.origin = file;

            }
            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.TextCorpus.java

/**
 * @return list of files in corpus/*from   ww  w. j  a va  2  s.  c om*/
 * @throws IOException 
 * @throws ZipException 
 */
@SuppressWarnings("unchecked")
protected HashMap<URI, InputStream> getEntries() throws Exception {

    HashMap<URI, InputStream> entries = new HashMap<URI, InputStream>();

    if (corpusFileMediaType == MediaType.ZIP) {
        ZipFile zippedCorpusDir = new ZipFile(corpus);
        Enumeration<? extends ZipEntry> zipEntries = zippedCorpusDir.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            if (!zipEntry.isDirectory()) {

                String uriValue = corpus.toURI().toString() + "/";
                String entryName = zipEntry.getName();
                uriValue += URLEncoder.encode(entryName, "utf-8");

                entries.put(new URI(uriValue), zippedCorpusDir.getInputStream(zipEntry));
            }
        }
    } else if (corpusFileMediaType == MediaType.DIRECTORY) {
        for (File f : corpus.listFiles()) {
            entries.put(f.toURI(), new FileInputStream(f));
        }
    }

    return entries;
}

From source file:com.thoughtworks.go.util.ZipUtilTest.java

private void assertContent(File targetZipFile, String file, String expectedContent) throws IOException {
    ZipFile actualZip = new ZipFile(targetZipFile);
    ZipEntry entry = actualZip.getEntry(file);
    assertThat(entry).isNotNull();/* w ww .j a  va  2  s  .co  m*/
    assertThat(IOUtils.toString(actualZip.getInputStream(entry), UTF_8)).isEqualTo(expectedContent);
}

From source file:org.envirocar.app.util.Util.java

/**
 * method to get the current version//from ww  w  . j  a v a  2s  .  co  m
 * 
 */
public static String getVersionString(Context ctx) {
    StringBuilder out = new StringBuilder("Version ");
    try {
        out.append(getVersionStringShort(ctx));
        out.append(" (");
        out.append(ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionCode);
        out.append("), ");
    } catch (NameNotFoundException e) {
        logger.warn(e.getMessage(), e);
    }
    try {
        ApplicationInfo ai = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        out.append(SimpleDateFormat.getInstance().format(new java.util.Date(time)));
        zf.close();
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }

    return out.toString();
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static void addToCache(String cacheName, Game game)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    logger.log(Level.FINEST, "Saving file {0} to cache", cacheName);
    File file = new File("archive.zip");
    File file1 = null;//from   w ww.j  a va2s. c  om
    if (file.exists()) {
        //copy to archive1, return
        file1 = new File("archive1.zip");
        if (file1.exists()) {
            if (!file1.delete()) {
                logger.log(Level.WARNING, "Unable to delete file {0}", file1.getCanonicalPath());
                return;
            }
        }
        if (!file.renameTo(file1)) {
            logger.log(Level.WARNING, "Unable to rename file {0} to {1}",
                    new Object[] { file.getCanonicalPath(), file1.getCanonicalPath() });
            // unable to move to archive1 and whole operation fails!!!
            return;
        }
    }

    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file))) {
        out.setLevel(9);
        // name the file inside the zip  file 
        out.putNextEntry(new ZipEntry(cacheName));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
        JsonWriter jsonWriter = new JsonWriter(outputStreamWriter);
        jsonWriter.setIndent("  ");
        builder.create().toJson(game, Game.class, jsonWriter);
        jsonWriter.flush();

        if (file1 != null) {
            try (ZipFile zipFile = new ZipFile(file1)) {
                Enumeration<? extends ZipEntry> files = zipFile.entries();
                while (files.hasMoreElements()) {
                    ZipEntry entry = files.nextElement();
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        out.putNextEntry(new ZipEntry(entry.getName()));

                        IOUtils.copy(in, out);
                    }
                }
            }
            file1.delete();

        }
    }
}