Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:ZipHandler.java

/**
 * unzipps a zip file placed at <zipURL> to path <xmlURL>
 * @param zipURL/*from   ww  w  .j  a  va2  s  . com*/
 * @param xmlURL
 */
public static void unZip(String zipURL, String xmlURL) throws IOException {
    FileOutputStream fosBLOB = new FileOutputStream(new File("c:\\"));
    FileOutputStream fosCLOB = new FileOutputStream(new File("c:\\"));
    FileInputStream fis = new FileInputStream(new File(zipURL));
    ZipInputStream zis = new ZipInputStream(fis);
    FileOutputStream fos = new FileOutputStream(xmlURL);
    ZipEntry ze = zis.getNextEntry();
    ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
    ze = zis.getNextEntry();
    ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
    ze = zis.getNextEntry();
    ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
    fos.flush();
    fis.close();
    fos.close();
    fosCLOB.close();
    fosBLOB.close();
    zis.close();
}

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.
 * //w  w  w.ja  v  a 2 s  .  com
 * @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.seer.datacruncher.streams.ZipStreamTest.java

@Test
public void testZipStream() {
    String fileName = properties.getProperty("zip_test_stream_file_name");
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(stream_file_path + fileName);
    byte[] arr = null;
    try {/*from www. j  a va  2  s.c  o  m*/
        arr = IOUtils.toByteArray(in);
    } catch (IOException e) {
        assertTrue("IOException while Zip test file reading", false);
    }

    ZipInputStream inStream = null;
    try {
        inStream = new ZipInputStream(new ByteArrayInputStream(arr));
        ZipEntry entry;
        while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                DatastreamsInput datastreamsInput = new DatastreamsInput();
                datastreamsInput.setUploadedFileName(entry.getName());
                byte[] byteInput = IOUtils.toByteArray(inStream);
                String res = datastreamsInput.datastreamsInput(null, (Long) schemaEntity.getIdSchema(),
                        byteInput, true);
                assertTrue("Zip file validation failed", Boolean.parseBoolean(res));
            }
            inStream.closeEntry();
        }
    } catch (IOException ex) {
        assertTrue("Error occured during fetch records from ZIP file.", false);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
    }
}

From source file:com.ibm.jaggr.core.util.ZipUtil.java

/**
 * Extracts the specified zip file to the specified location. If {@code selector} is specified,
 * then only the entry specified by {@code selector} (if {@code selector} is a filename) or the
 * contents of the directory specified by {@code selector} (if {@code selector} is a directory
 * name) will be extracted. If {@code selector} specifies a directory, then the contents of the
 * directory in the zip file will be rooted at {@code destDir} when extracted.
 *
 * @param zipFile//w w w  .  jav a  2 s .co  m
 *            the {@link File} object for the file to unzip
 * @param destDir
 *            the {@link File} object for the target directory
 * @param selector
 *            The name of a file or directory to extract
 * @throws IOException
 */
public static void unzip(File zipFile, File destDir, String selector) throws IOException {
    final String sourceMethod = "unzip"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceClass, sourceMethod, new Object[] { zipFile, destDir });
    }

    boolean selectorIsFolder = selector != null && selector.charAt(selector.length() - 1) == '/';
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
    try {
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String entryName = entry.getName();
            if (selector == null || !selectorIsFolder && entryName.equals(selector) || selectorIsFolder
                    && entryName.startsWith(selector) && entryName.length() != selector.length()) {
                if (selector != null) {
                    if (selectorIsFolder) {
                        // selector is a directory.  Strip selected path
                        entryName = entryName.substring(selector.length());
                    } else {
                        // selector is a filename.  Extract the filename portion of the path
                        int idx = entryName.lastIndexOf("/"); //$NON-NLS-1$
                        if (idx != -1) {
                            entryName = entryName.substring(idx + 1);
                        }
                    }
                }
                File file = new File(destDir, entryName.replace("/", File.separator)); //$NON-NLS-1$
                if (!entry.isDirectory()) {
                    // if the entry is a file, extract it
                    extractFile(entry, zipIn, file);
                } else {
                    // if the entry is a directory, make the directory
                    extractDirectory(entry, file);
                }
                zipIn.closeEntry();
            }
            entry = zipIn.getNextEntry();
        }
    } finally {
        zipIn.close();
    }

    if (isTraceLogging) {
        log.exiting(sourceClass, sourceMethod);
    }
}

From source file:com.matze5800.paupdater.Functions.java

public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException {
    File tempFile = new File(Environment.getExternalStorageDirectory() + "/pa_updater", "temp_kernel.zip");
    tempFile.delete();/*from   ww w  . jav  a 2  s.c  o  m*/

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {

            out.putNextEntry(new ZipEntry(name));

            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    zin.close();

    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        out.putNextEntry(new ZipEntry(files[i].getName()));

        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
}

From source file:com.wso2mobile.mam.packageExtractor.ZipFileReading.java

public String readAndroidManifestFile(String filePath) {
    String xml = "";
    try {/*from w w w  .  j av a2  s .  co m*/
        ZipInputStream stream = new ZipInputStream(new FileInputStream(filePath));
        try {
            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                if (entry.getName().equals("AndroidManifest.xml")) {
                    StringBuilder builder = new StringBuilder();
                    xml = AndroidXMLParsing.decompressXML(IOUtils.toByteArray(stream));
                }
            }
        } finally {
            stream.close();
        }
        Document doc = loadXMLFromString(xml);
        doc.getDocumentElement().normalize();
        JSONObject obj = new JSONObject();
        obj.put("version", doc.getDocumentElement().getAttribute("versionName"));
        obj.put("package", doc.getDocumentElement().getAttribute("package"));
        xml = obj.toJSONString();
    } catch (Exception e) {
        xml = "Exception occured " + e;
    }
    return xml;
}

From source file:be.fedict.eid.dss.document.zip.ZIPSignatureOutputStream.java

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

    byte[] signatureData = toByteArray();

    /*//from  w ww.j a v a2 s. c  o  m
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ZIP package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.javacreed.examples.lang.DynamicClassLoader.java

public void loadJar(final InputStream in) throws IOException {
    try (BufferedInputStream bis = new BufferedInputStream(in); ZipInputStream zis = new ZipInputStream(bis)) {
        for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
            if (ze.isDirectory()) {
                continue;
            }//from w ww .j ava  2 s.  c o m

            final String name = ze.getName();
            final String canonicalName = StringUtils.removeEnd(name, ".class").replaceAll("[\\/]", ".");
            final byte[] classBytes = IOUtils.toByteArray(zis);
            if (loadedClasses.putIfAbsent(canonicalName, classBytes) == null) {
                DynamicClassLoader.LOGGER.debug("Loading class: {} of {} bytes", canonicalName,
                        classBytes.length);
            } else {
                DynamicClassLoader.LOGGER.debug("Skipping class: {} of {} bytes as onle already exists",
                        canonicalName, classBytes.length);
            }
        }
    }
}

From source file:org.eclipse.skalli.model.ext.maven.internal.GitBlitMavenPomResolver.java

@Override
protected InputStream asPomInputStream(HttpEntity entity, String relativePath) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(entity.getContent());
    return ZipHelper.getEntry(zipInputStream, getPomFileName(relativePath));
}

From source file:com.jadarstudios.rankcapes.forge.cape.CapePack.java

/**
 * Parses the Zip file in memory./*from www  .  j a  va2  s. c  om*/
 *
 * @param input the bytes of a valid zip file
 */
private void parsePack(byte[] input) {
    try {
        ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(input));

        String metadata = "";

        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            String name = entry.getName();

            if (name.endsWith(".png")) {
                // remove file extension from the name.
                name = FilenameUtils.removeExtension(name);

                StaticCape cape = this.loadCape(name, zipInput);
                this.unprocessedCapes.put(name, cape);
            } else if (name.endsWith(".mcmeta")) {
                // parses the pack metadata.
                InputStreamReader streamReader = new InputStreamReader(zipInput);
                while (streamReader.ready()) {
                    metadata += (char) streamReader.read();
                }
            }
        }
        if (!Strings.isNullOrEmpty(metadata)) {
            this.parsePackMetadata(StringUtils.remove(metadata, (char) 65535));
        } else {
            RankCapesForge.log.warn("Cape Pack metadata is missing!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}