Example usage for java.util.zip ZipEntry getSize

List of usage examples for java.util.zip ZipEntry getSize

Introduction

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

Prototype

public long getSize() 

Source Link

Document

Returns the uncompressed size of the entry data.

Usage

From source file:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();/*  www. j  a v  a  2s  . c o m*/

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

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

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

From source file:net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats.ZipReadTask.java

/**
 * @see java.lang.Runnable#run()/* ww w  . j  a v  a 2 s. c o  m*/
 */
public void run() {

    // Update task status
    setStatus(TaskStatus.PROCESSING);
    logger.info("Started opening compressed file " + file);

    try {

        // Name of the uncompressed file
        String newName = file.getName();
        if (newName.toLowerCase().endsWith(".zip") || newName.toLowerCase().endsWith(".gz")) {
            newName = FilenameUtils.removeExtension(newName);
        }

        // Create decompressing stream
        FileInputStream fis = new FileInputStream(file);
        InputStream is;
        long decompressedSize = 0;
        switch (fileType) {
        case ZIP:
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            newName = entry.getName();
            decompressedSize = entry.getSize();
            if (decompressedSize < 0)
                decompressedSize = 0;
            is = zis;
            break;
        case GZIP:
            is = new GZIPInputStream(fis);
            decompressedSize = (long) (file.length() * 1.5); // Ballpark a
                                                             // decompressedFile
                                                             // size so the
                                                             // GUI can show
                                                             // progress
            if (decompressedSize < 0)
                decompressedSize = 0;
            break;
        default:
            setErrorMessage("Cannot decompress file type: " + fileType);
            setStatus(TaskStatus.ERROR);
            return;
        }

        tmpDir = Files.createTempDir();
        tmpFile = new File(tmpDir, newName);
        logger.finest("Decompressing to file " + tmpFile);
        tmpFile.deleteOnExit();
        tmpDir.deleteOnExit();
        FileOutputStream ous = new FileOutputStream(tmpFile);

        // Decompress the contents
        copy = new StreamCopy();
        copy.copy(is, ous, decompressedSize);

        // Close the streams
        is.close();
        ous.close();

        if (isCanceled())
            return;

        // Find the type of the decompressed file
        RawDataFileType fileType = RawDataFileTypeDetector.detectDataFileType(tmpFile);
        logger.finest("File " + tmpFile + " type detected as " + fileType);

        if (fileType == null) {
            setErrorMessage("Could not determine the file type of file " + newName);
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the import module on the decompressed file
        RawDataFileWriter newMZmineFile = MZmineCore.createNewFile(newName);
        decompressedOpeningTask = RawDataImportModule.createOpeningTask(fileType, project, tmpFile,
                newMZmineFile);

        if (decompressedOpeningTask == null) {
            setErrorMessage("File type " + fileType + " of file " + newName + " is not supported.");
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the underlying task
        decompressedOpeningTask.run();

        // Delete the temporary folder
        tmpFile.delete();
        tmpDir.delete();

        if (isCanceled())
            return;

    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Could not open file " + file.getPath(), e);
        setErrorMessage(ExceptionUtils.exceptionToString(e));
        setStatus(TaskStatus.ERROR);
        return;
    }

    logger.info("Finished opening compressed file " + file);

    // Update task status
    setStatus(TaskStatus.FINISHED);

}

From source file:com.jkoolcloud.tnt4j.streams.inputs.ZipLineStream.java

private boolean hasNextEntry() throws IOException {
    if (zipStream instanceof ZipInputStream) {
        ZipInputStream zis = (ZipInputStream) zipStream;

        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String entryName = entry.getName();

            if (entry.getSize() != 0 && (zipEntriesMask == null || entryName.matches(zipEntriesMask))) {
                totalBytesCount += entry.getSize();
                lineReader = new LineNumberReader(new BufferedReader(new InputStreamReader(zis)));
                lineNumber = 0;// w  w w  .j  a v a  2  s .  com

                logger().log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ZipLineStream.opening.entry"), entryName);

                return true;
            }
        }
    }

    return false;
}

From source file:JarResources.java

private String dumpZipEntry(ZipEntry ze) {
    StringBuffer sb = new StringBuffer();
    if (ze.isDirectory()) {
        sb.append("d ");
    } else {//from  w  ww  .  j  av  a2  s  .  co m
        sb.append("f ");
    }

    if (ze.getMethod() == ZipEntry.STORED) {
        sb.append("stored   ");
    } else {
        sb.append("defalted ");
    }

    sb.append(ze.getName());
    sb.append("\t");
    sb.append("" + ze.getSize());
    if (ze.getMethod() == ZipEntry.DEFLATED) {
        sb.append("/" + ze.getCompressedSize());
    }

    return (sb.toString());
}

From source file:org.jboss.as.test.integration.jdr.mgmt.JdrReportManagmentTestCase.java

private void validateEntryNotEmpty(String fileName, ZipFile reportZip, String reportName) {
    String entryInZip = reportName + "/" + fileName;
    ZipEntry entry = reportZip.getEntry(entryInZip);
    Assert.assertNotNull("Report entry " + fileName + " missing from JDR report " + reportZip.getName(), entry);
    Assert.assertTrue("Report entry " + fileName + " was empty or could not be determined",
            entry.getSize() > 0);
}

From source file:com.khubla.simpleioc.classlibrary.ClassLibrary.java

/**
 * find all the classes in a jar file/*from  ww  w  .  j av a2  s . c o  m*/
 */
private List<Class<?>> crackJar(String jarfile) throws Exception {
    try {
        /*
         * the ret
         */
        final List<Class<?>> ret = new ArrayList<Class<?>>();
        /*
         * the jar
         */
        final FileInputStream fis = new FileInputStream(jarfile);
        final ZipInputStream zip_inputstream = new ZipInputStream(fis);
        ZipEntry current_zip_entry = null;
        while ((current_zip_entry = zip_inputstream.getNextEntry()) != null) {
            if (current_zip_entry.getName().endsWith(".class")) {
                if (current_zip_entry.getSize() > 0) {
                    final ClassNode classNode = new ClassNode();
                    final ClassReader cr = new ClassReader(zip_inputstream);
                    cr.accept(classNode, 0);
                    if (annotated(classNode)) {
                        ret.add(Class.forName(classNode.name.replaceAll("/", ".")));
                        log.debug("Found " + classNode.name + " in " + jarfile);
                    }
                }
            }
        }
        zip_inputstream.close();
        fis.close();
        return ret;
    } catch (final Throwable e) {
        throw new Exception("Exception in crackJar for jar '" + jarfile + "'", e);
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected String getZipEntryText(ZipFile zipFile, ZipEntry ze) {
    String toReturn = "";
    try {//from w ww  .  ja va 2s.  com
        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(ze));
        byte[] bytes = new byte[(int) (ze.getSize())];
        is.read(bytes, 0, bytes.length);
        is.close();
        toReturn = new String(bytes);
    } catch (Exception e) {
        // nothing
    }
    return toReturn;
}

From source file:org.pentaho.platform.plugin.services.importexport.legacy.ZipSolutionRepositoryImportSource.java

/**
 * Initializes the ImportSource - it will read the zip input stream and create the list of files
 *///from   w w w  . jav a2s  .c o  m
protected void initialize() throws org.pentaho.platform.plugin.services.importexport.InitializationException {
    try {
        ZipEntry entry = zipInputStream.getNextEntry();
        while (entry != null) {
            final String entryName = RepositoryFilenameUtils.separatorsToRepository(entry.getName());
            final String extension = RepositoryFilenameUtils.getExtension(entryName);
            File tempFile = null;
            boolean isDir = entry.getSize() == 0;
            if (!isDir) {
                tempFile = File.createTempFile("zip", null);
                tempFile.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(tempFile);
                IOUtils.copy(zipInputStream, fos);
                fos.close();
            }
            File file = new File(entryName);
            RepositoryFile repoFile = new RepositoryFile.Builder(file.getName()).folder(isDir).hidden(false)
                    .build();
            String parentDir = new File(entryName).getParent() == null ? "/"
                    : new File(entryName).getParent() + "/";
            org.pentaho.platform.plugin.services.importexport.RepositoryFileBundle repoFileBundle = new org.pentaho.platform.plugin.services.importexport.RepositoryFileBundle(
                    repoFile, null, parentDir, tempFile, charSet, getMimeType(extension.toLowerCase()));
            files.add(repoFileBundle);
            zipInputStream.closeEntry();
            entry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    } catch (IOException exception) {
        // TODO I18N
        final String errorMessage = Messages.getInstance().getErrorString("", exception.getLocalizedMessage());
        throw new org.pentaho.platform.plugin.services.importexport.InitializationException(errorMessage,
                exception);
    }
}

From source file:com.fujitsu.dc.core.eventlog.ArchiveLogCollection.java

/**
 * ????.//from ww w  . ja v  a2  s . com
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:com.marklogic.contentpump.ArchiveRecordReader.java

@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    if (zipIn == null) {
        hasNext = false;/*from w ww .  j av  a2  s .  c om*/
        return false;
    }

    ZipEntry zipEntry;
    ZipInputStream zis = (ZipInputStream) zipIn;
    if (value == null) {
        value = new DatabaseDocumentWithMeta();
    }
    while ((zipEntry = zis.getNextEntry()) != null) {
        subId = zipEntry.getName();
        long length = zipEntry.getSize();
        if (subId.endsWith(DocumentMetadata.NAKED)) {
            ((DatabaseDocumentWithMeta) value).setMeta(getMetadataFromStream(length));
            String uri = subId.substring(0, subId.length() - DocumentMetadata.NAKED.length());
            setKey(uri, 0, 0, false);
            value.setContent(null);
            count++;
            return true;
        }
        if (count % 2 == 0 && subId.endsWith(DocumentMetadata.EXTENSION)) {
            ((DatabaseDocumentWithMeta) value).setMeta(getMetadataFromStream(length));
            count++;
            continue;
        }
        // no meta data
        if (count % 2 == 0 && !allowEmptyMeta) {
            setSkipKey(0, 0, "Missing metadata");
            return true;
        } else {
            setKey(subId, 0, 0, false);
            readDocFromStream(length, (DatabaseDocument) value);
            count++;
            return true;
        }
    }
    //end of a zip
    if (iterator != null && iterator.hasNext()) {
        close();
        initStream(iterator.next());
        return nextKeyValue();
    } else {
        hasNext = false;
        return false;
    }
}