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:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Check if an ODF package is self-contained, i.e. content files don't have
 * OLE objects linked to external files//from  www . ja va 2  s  .c om
 * 
 * @param odfUrl
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static boolean isSelfContained(URL odfUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    InputStream odfInputStream = odfUrl.openStream();
    List zipEntries = getZipEntriesAsList(odfInputStream);

    odfInputStream = odfUrl.openStream();
    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    XPathFactory factory = XPathFactory.newInstance();
    /* Maybe a bit overkill, but implementations can use other prefixes */
    ODFNamespaceContext namespaceContext = new ODFNamespaceContext();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expression = xpath.compile("//draw:object/@xlink:href|" + "//draw:object-ole/@xlink:href|"
            + "//draw:image/@xlink:href|" + "//draw:floating-frame/@xlink:href");

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (isContentFile(zipEntry)) {
            /* TODO: pure SAX is probably more memory-efficient */
            Document content = ODFUtil.loadDocument(odfZipInputStream);
            NodeList nodes = (NodeList) expression.evaluate(content, XPathConstants.NODESET);
            return checkNodes(nodes, zipEntries);
        }
    }
    return true;
}

From source file:com.googlecode.dex2jar.reader.DexFileReader.java

/**
 * read the dex file from byte array, if the byte array is a zip stream, it will return the content of classes.dex
 * in the zip stream.//from   www  .j  av a  2 s. c o  m
 * 
 * @param data
 * @return
 * @throws IOException
 */
public static byte[] readDex(byte[] data) throws IOException {
    if ("de".equals(new String(data, 0, 2))) {// dex/y
        return data;
    } else if ("PK".equals(new String(data, 0, 2))) {// ZIP
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(new ByteArrayInputStream(data));
            for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
                if (entry.getName().equals("classes.dex")) {
                    return IOUtils.toByteArray(zis);
                }
            }
        } finally {
            IOUtils.closeQuietly(zis);
        }
    }
    throw new RuntimeException("the src file not a .dex, .odex or zip file");
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

/**
 * zip/*from   w ww  .  j a  v a  2  s  .  c  o m*/
 *
 * @param zipFile
 * @param file
 * @param destPath
 * @param overwrite ?
 * @throws java.io.IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Close the streams
    zin.close();
    out.close();
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

public static void splitZipToFolder(File inputFile, File outputFolder, Set<String> includeEnties)
        throws IOException {
    if (!outputFolder.exists()) {
        outputFolder.mkdirs();//from  www. j  a  v  a 2s  .c o  m
    }
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                continue;
            }
            File destFile = new File(outputFolder, name);
            destFile.getParentFile().mkdirs();
            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            FileOutputStream fout = FileUtils.openOutputStream(destFile);
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }
            fout.close();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
}

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(java.io.InputStream inputStream, String dir) throws Exception {
    File file = new File(dir);
    FileUtils.mkdirsWithExistsCheck(file);
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {/*www . j a  va2  s.  c  o m*/
        zipInputStream = new ZipInputStream(inputStream);

        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();

            s1 = convertEncoding(s1);

            String s2 = dir + sp + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }
            if (isDirectory) {
                continue;
            }
            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:de.innovationgate.wgpublisher.plugins.WGAPlugin.java

public static Configuration loadConfiguration(File file, boolean full)
        throws FileNotFoundException, IOException, InvalidCSConfigVersionException {

    if (!file.exists()) {
        return null;
    }/*from  www.  j av a 2  s. com*/

    file = WGUtils.resolveDirLink(file);

    DesignDefinition syncInfo = null;
    CSConfig csConfig = null;
    OverlayData overlayData = null;
    String licenseText = null;

    // Normal plugin file
    if (file.isFile()) {
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {

                String entryName = entry.getName();
                if (entryName.equals(DesignDirectory.DESIGN_DEFINITION_FILE)
                        || entryName.equals(DesignDirectory.SYNCINFO_FILE)) {
                    TemporaryFile tempFile = new TemporaryFile("design", zipIn, WGFactory.getTempDir());
                    syncInfo = DesignDefinition.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.CSCONFIG_PATH)) {
                    TemporaryFile tempFile = new TemporaryFile("csconfig", zipIn, WGFactory.getTempDir());
                    csConfig = CSConfig.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.LICENSE_PATH)) {
                    licenseText = WGUtils.readString(new InputStreamReader(zipIn, "UTF-8")).trim();
                } else if (entryName.equals(SystemContainerManager.OVERLAY_DATA_PATH)) {
                    try {
                        overlayData = OverlayData.read(zipIn);
                    } catch (Exception e) {
                        Logger.getLogger("wga.plugins").error(
                                "Exception reading overlay data from plugin file " + file.getAbsolutePath(), e);
                    }
                }

                if (syncInfo != null && csConfig != null) {
                    if (!full || overlayData != null) {
                        break;
                    }
                }
            }
        } finally {
            zipIn.close();
        }
    }

    // Developer plugin folder
    else {
        File syncInfoFile = DesignDirectory.getDesignDefinitionFile(file);
        if (syncInfoFile.exists()) {
            syncInfo = DesignDefinition.load(syncInfoFile);
        }
        File csConfigFile = new File(file, SystemContainerManager.CSCONFIG_PATH);
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }
        File licenseTextFile = new File(file, SystemContainerManager.LICENSE_PATH);
        if (licenseTextFile.exists()) {
            Reader reader = new InputStreamReader(new FileInputStream(licenseTextFile), "UTF-8");
            licenseText = WGUtils.readString(reader).trim();
            reader.close();
        }
        File overlayDataFile = new File(file, SystemContainerManager.OVERLAY_DATA_PATH);
        if (overlayDataFile.exists()) {
            try {
                InputStream stream = new FileInputStream(overlayDataFile);
                overlayData = OverlayData.read(stream);
                stream.close();
            } catch (Exception e) {
                Logger.getLogger("wga.plugins").error(
                        "Exception reading overlay data from plugin directory " + file.getAbsolutePath(), e);
            }
        }

    }

    if (syncInfo != null && csConfig != null && csConfig.getPluginConfig() != null) {
        return new Configuration(syncInfo, csConfig, licenseText, overlayData);
    } else {
        return null;
    }

}

From source file:com.glaf.core.util.ZipUtils.java

public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream) {
    Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>();
    java.util.zip.ZipEntry zipEntry = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    byte tmpByte[] = null;
    try {//from   ww  w .j  av  a 2s  . c  o m
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            tmpByte = new byte[BUFFER];
            baos = new ByteArrayOutputStream();
            bos = new BufferedOutputStream(baos, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) {
                bos.write(tmpByte, 0, i);
            }
            bos.flush();
            byte[] bytes = baos.toByteArray();
            IOUtils.closeStream(baos);
            IOUtils.closeStream(baos);
            zipMap.put(zipEntry.getName(), bytes);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(baos);
        IOUtils.closeStream(baos);
    }
    return zipMap;
}

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(java.io.InputStream inputStream, String path, List<String> excludes) throws Exception {
    File file = new File(path);
    FileUtils.mkdirsWithExistsCheck(file);
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {//from w  w w  . j  a va 2 s.c  o m
        zipInputStream = new ZipInputStream(inputStream);
        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();
            String ext = FileUtils.getFileExt(s1);
            if (excludes.contains(ext) || excludes.contains(ext.toLowerCase())) {
                continue;
            }

            s1 = convertEncoding(s1);

            String s2 = path + sp + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }
            if (isDirectory) {
                continue;
            }
            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

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

private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;
    ZipOutputStream outJar = null;

    try {//from   w w  w .ja  v  a  2 s  . c  o m
        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 (MarkerTransformer 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.taobao.android.tpatch.utils.JarSplitUtils.java

public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException {
    if (outputFile.exists()) {
        FileUtils.deleteQuietly(outputFile);
    }/*www . j ava2  s. com*/
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
}