Example usage for java.util.zip ZipInputStream getNextEntry

List of usage examples for java.util.zip ZipInputStream getNextEntry

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:org.opendatakit.api.forms.FormService.java

static Map<String, byte[]> processZipInputStream(ZipInputStream zipInputStream) throws IOException {
    int c;/*from   w ww .  j  a va  2 s .co m*/
    Map<String, byte[]> files = new HashMap<>();
    byte buffer[] = new byte[2084];
    ByteArrayOutputStream tempBAOS;
    ZipEntry zipEntry;
    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        if (!(zipEntry.isDirectory())) {
            tempBAOS = new ByteArrayOutputStream();
            while ((c = zipInputStream.read(buffer, 0, 2048)) > -1) {
                tempBAOS.write(buffer, 0, c);
            }
            files.put("tables" + BasicConsts.FORWARDSLASH + zipEntry.getName(), tempBAOS.toByteArray());
        }
    }
    return files;
}

From source file:com.alibaba.antx.util.ZipUtil.java

/**
 * zip/*from w  ww. j a v a2 s. c o  m*/
 *
 * @param istream   ?
 * @param todir     
 * @param overwrite ?
 * @throws IOException Zip?
 */
public static void expandFile(InputStream istream, File todir, boolean overwrite) throws IOException {
    ZipInputStream zipStream = null;

    if (!(istream instanceof BufferedInputStream)) {
        istream = new BufferedInputStream(istream, 8192);
    }

    try {
        zipStream = new ZipInputStream(istream);

        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {
            extractFile(todir, zipStream, zipEntry, overwrite);
        }

        log.info("expand complete");
    } finally {
        if (zipStream != null) {
            try {
                zipStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransform.java

private static void extractJar(@NonNull File outJarFolder, @NonNull File jarFile, boolean extractCode)
        throws IOException {
    mkdirs(outJarFolder);/*from  w w w  . ja  va2s.c o m*/
    HashSet<String> lowerCaseNames = new HashSet<>();
    boolean foundCaseInsensitiveIssue = false;

    try (Closer closer = Closer.create()) {
        FileInputStream fis = closer.register(new FileInputStream(jarFile));
        ZipInputStream zis = closer.register(new ZipInputStream(fis));
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            try {
                String name = entry.getName();

                // do not take directories
                if (entry.isDirectory()) {
                    continue;
                }

                foundCaseInsensitiveIssue = foundCaseInsensitiveIssue
                        || !lowerCaseNames.add(name.toLowerCase(Locale.US));

                Action action = getAction(name, extractCode);
                if (action == Action.COPY) {
                    File outputFile = new File(outJarFolder, name.replace('/', File.separatorChar));
                    mkdirs(outputFile.getParentFile());

                    try (Closer closer2 = Closer.create()) {
                        java.io.OutputStream outputStream = closer2
                                .register(new BufferedOutputStream(new FileOutputStream(outputFile)));
                        ByteStreams.copy(zis, outputStream);
                        outputStream.flush();
                    }
                }
            } finally {
                zis.closeEntry();
            }
        }

    }

    if (foundCaseInsensitiveIssue) {
        LOGGER.error(
                "Jar '{}' contains multiple entries which will map to "
                        + "the same file on case insensitive file systems.\n"
                        + "This can be caused by obfuscation with useMixedCaseClassNames.\n"
                        + "This build will be incorrect on case insensitive " + "file systems.",
                jarFile.getAbsolutePath());
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Read a given file from the ZIP file and store it in a temporary file. The
 * temporary file is set to be deleted on exit of application.
 * /*from  w  w  w . j  a  v a  2 s. c  o  m*/
 * @param zipFile
 *            the zip file from which the file needs to be read
 * 
 * @param fileName
 *            the name of the file that needs to be extracted
 * 
 * @return the {@link File} handle for the extracted file in the temp
 *         directory
 * 
 * @throws IllegalArgumentException
 *             if the zipFile is <code>null</code> or the fileName is
 *             <code>null</code> or empty.
 */
public static File readFileFromZip(File zipFile, String fileName) throws FileNotFoundException, IOException {
    if (zipFile == null) {
        throw new IllegalArgumentException("zip file to extract from cannot be null");
    }

    if (AssertUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("the filename to extract cannot be null/empty");
    }

    LOGGER.debug("Reading {} from {}", fileName, zipFile.getAbsolutePath());

    ZipInputStream stream = null;
    BufferedOutputStream outStream = null;
    File tempFile = null;

    try {
        byte[] buf = new byte[1024];
        stream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String entryName = entry.getName();
            if (entryName.equals(fileName)) {
                tempFile = File.createTempFile(FilenameUtils.getName(entryName),
                        FilenameUtils.getExtension(entryName));
                tempFile.deleteOnExit();

                outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                int readBytes;
                while ((readBytes = stream.read(buf, 0, 1024)) > -1) {
                    outStream.write(buf, 0, readBytes);
                }

                stream.close();
                outStream.close();

                return tempFile;
            }
        }
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(outStream);
    }

    return tempFile;
}

From source file:com.microsoft.intellij.AzurePlugin.java

private static void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();/*from  w w  w  .j  a v  a2s  . co m*/
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = destDirectory + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void expandZip(String zipFileName, String rootDir, String prefixDir)
        throws FileNotFoundException, IOException {
    Engine.logEngine.debug("Expanding the zip file " + zipFileName);

    // Creating the root directory
    File ftmp = new File(rootDir);
    if (!ftmp.exists()) {
        ftmp.mkdirs();/*from w  w  w  .jav  a 2s  . c  o  m*/
        Engine.logEngine.debug("Root directory created");
    }

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));

    try {
        ZipEntry entry;
        int prefixSize = prefixDir != null ? prefixDir.length() : 0;

        while ((entry = zis.getNextEntry()) != null) {
            // Ignoring directories
            if (entry.isDirectory()) {

            } else {

                String entryName = entry.getName();
                Engine.logEngine.debug("+ Analyzing the entry: " + entryName);

                try {
                    // Ignore entry if does not belong to the project directory
                    if ((prefixDir == null) || entryName.startsWith(prefixDir)) {

                        // Ignore entry from _data or _private directory
                        if ((entryName.indexOf("/_data/") != prefixSize)
                                && (entryName.indexOf("/_private/") != prefixSize)) {
                            Engine.logEngine.debug("  The entry is accepted");
                            String s1 = rootDir + "/" + entryName;
                            String dir = s1.substring(0, s1.lastIndexOf('/'));

                            // Creating the directory if needed
                            ftmp = new File(dir);
                            if (!ftmp.exists()) {
                                ftmp.mkdirs();
                                Engine.logEngine.debug("  Directory created");
                            }

                            // Writing the files to the disk
                            File file = new File(rootDir + "/" + entryName);
                            FileOutputStream fos = new FileOutputStream(file);
                            try {
                                IOUtils.copy(zis, fos);
                            } finally {
                                fos.close();
                            }
                            file.setLastModified(entry.getTime());
                            Engine.logEngine.debug("  File written to: " + rootDir + "/" + entryName);
                        }
                    }
                } catch (IOException e) {
                    Engine.logEngine.error(
                            "Unable to expand the ZIP entry \"" + entryName + "\": " + e.getMessage(), e);
                }
            }
        }
    } finally {
        zis.close();
    }
}

From source file:com.nextep.designer.repository.services.impl.RepositoryUpdaterService.java

/**
 * Creates the specified delivery (ZIP resource file) on the temporary directory of the local
 * file system./*from  w w  w.  jav a 2 s . co m*/
 * 
 * @param deliveryResource java resource zip file
 * @return a <code>String</code> representing the absolute path to the delivery root directory.
 */
private static String createTempDelivery(String deliveryResource) {
    InputStream is = RepositoryUpdaterService.class.getResourceAsStream(deliveryResource);
    if (is == null) {
        throw new ErrorException("Unable to load delivery file: " + deliveryResource); //$NON-NLS-1$
    }

    final String exportLoc = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
    ZipInputStream zipInput = new ZipInputStream(is);
    ZipEntry entry = null;
    String rootDeliveryDir = null;
    try {
        while ((entry = zipInput.getNextEntry()) != null) {
            File targetFile = new File(exportLoc, entry.getName());

            if (rootDeliveryDir == null) {
                /*
                 * Initialize the delivery root directory value by searching recursively for the
                 * shallowest directory in the path.
                 */
                rootDeliveryDir = getDeliveryRootPath(targetFile, new File(exportLoc));
            }

            if (entry.isDirectory()) {
                targetFile.mkdirs();
            } else {
                File targetDir = targetFile.getParentFile();
                if (!targetDir.exists()) {
                    /*
                     * Creates the directory including any necessary but nonexistent parent
                     * directories.
                     */
                    targetDir.mkdirs();
                }

                FileOutputStream outFile = new FileOutputStream(targetFile);
                copyStreams(zipInput, outFile);
                outFile.close();
            }
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new ErrorException(e);
    } finally {
        try {
            zipInput.close();
        } catch (IOException e) {
            throw new ErrorException(e);
        }
    }
    return rootDeliveryDir;
}

From source file:gov.va.chir.tagline.dao.FileDao.java

public static TagLineModel loadTagLineModel(final File file) throws Exception {
    final TagLineModel model = new TagLineModel();

    // Unzip each file to temp
    final File temp = new File(System.getProperty("java.io.tmpdir"));

    byte[] buffer = new byte[BUFFER_SIZE];

    final ZipInputStream zis = new ZipInputStream(new FileInputStream(file));

    ZipEntry entry = zis.getNextEntry();

    while (entry != null) {
        final String name = entry.getName();

        File tempFile = new File(temp, name);

        // Write out file
        final FileOutputStream fos = new FileOutputStream(tempFile);
        int len;//  w ww. j  av  a2  s  .  c  om
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();

        // Determine which file was written
        if (name.equalsIgnoreCase(FILENAME_FEATURES)) {
            model.setFeatures(loadFeatures(tempFile));
        } else if (name.equalsIgnoreCase(FILENAME_HEADER)) {
            model.setHeader(loadHeader(tempFile));
        } else if (name.equalsIgnoreCase(FILENAME_MODEL)) {
            model.setModel(loadModel(tempFile));
        } else {
            throw new IllegalStateException(String.format("Unknown file in TagLine model file (%s)", name));
        }

        // Delete temp file
        tempFile.delete();

        // Get next entry
        zis.closeEntry();
        entry = zis.getNextEntry();
    }

    zis.close();

    return model;
}

From source file:com.amalto.core.storage.hibernate.TypeMapping.java

private static Object _deserializeValue(Object value, FieldMetadata sourceField, FieldMetadata targetField) {
    if (targetField == null) {
        return value;
    }/*  w  w w . ja v a 2 s  .  co  m*/
    if (!targetField.isMany()) {
        Boolean targetZipped = targetField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        Boolean sourceZipped = sourceField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        if (Boolean.TRUE.equals(sourceZipped) && targetZipped == null) {
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(String.valueOf(value).getBytes("UTF-8")); //$NON-NLS-1$
                ZipInputStream zis = new ZipInputStream(new Base64InputStream(bis));
                byte[] buffer = new byte[1024];
                int read;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while (zis.getNextEntry() != null) {
                    while ((read = zis.read(buffer, 0, buffer.length)) > -1) {
                        bos.write(buffer, 0, read);
                    }
                }
                return new String(bos.toByteArray(), "UTF-8"); //$NON-NLS-1$
            } catch (IOException e) {
                throw new RuntimeException("Unexpected deflate exception", e); //$NON-NLS-1$
            }
        }
        String targetSQLType = sourceField.getType().getData(TypeMapping.SQL_TYPE);
        if (value != null && targetSQLType != null && SQL_TYPE_CLOB.equals(targetSQLType)) {
            try {
                Reader characterStream = ((Clob) value).getCharacterStream();
                return new String(IOUtils.toCharArray(characterStream)); // No need to close (Hibernate seems to
                                                                         // handle this).
            } catch (Exception e) {
                throw new RuntimeException("Unexpected read from clob exception", e); //$NON-NLS-1$
            }
        }
    }
    return value;
}

From source file:com.vividsolutions.jump.io.CompressedFile.java

/**
 * Searches through the .zip file looking for a file with the given extension.
 * Returns null if it doesn't find one.//from   ww w .  java  2s .c  o  m
 * 
 * @deprecated only used by very old data readers which only deliver the first file in zip file [ede 05.2012]
 */
public static String getInternalZipFnameByExtension(String extension, String compressedFile) throws Exception {
    // zip file
    String inside_zip_extension;
    InputStream IS_low = new FileInputStream(compressedFile);
    ZipInputStream fr_high = new ZipInputStream(IS_low);

    // need to find the correct file within the .zip file
    ZipEntry entry;

    entry = fr_high.getNextEntry();

    while (entry != null) {
        inside_zip_extension = entry.getName().substring(entry.getName().length() - extension.length());

        if (inside_zip_extension.compareToIgnoreCase(extension) == 0) {
            return (entry.getName());
        }

        entry = fr_high.getNextEntry();
    }

    return null;
}