Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

/**
 * Adds a zipfile from an inputStream to the aggregate zipfile.
 *
 * @param dirName name of the top-level directory that will be
 * @param inputStream the inputStream to the zipfile created in the aggregate zip file
 * @throws IOException/*ww  w . j a va  2  s.  c  o m*/
 * @throws BadInputZipFileException
 */
private void addZipFileFromInputStream(String dirName, long time, InputStream inputStream)
        throws IOException, BadInputZipFileException {
    // First pass: just scan through the contents of the
    // input file to make sure it's really valid.
    ZipInputStream zipInput = null;
    try {
        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new BadInputZipFileException("Input zip file seems to be invalid", e);
    } finally {
        if (zipInput != null)
            zipInput.close();
    }

    // FIXME: It is probably wrong to call reset() on any input stream; for my application the inputStream will only ByteArrayInputStream or FileInputStream
    inputStream.reset();

    // Second pass: read each entry from the input zip file,
    // writing it to the output file.
    zipInput = null;
    try {
        // add the root directory with the correct timestamp
        if (time > 0L) {
            // Create output entry
            ZipEntry outputEntry = new ZipEntry(dirName + "/");
            outputEntry.setTime(time);
            zipOutput.closeEntry();
        }

        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            try {
                String name = entry.getName();
                // Convert absolute paths to relative
                if (name.startsWith("/")) {
                    name = name.substring(1);
                }

                // Prepend directory name
                name = dirName + "/" + name;

                // Create output entry
                ZipEntry outputEntry = new ZipEntry(name);
                if (time > 0L)
                    outputEntry.setTime(time);
                zipOutput.putNextEntry(outputEntry);

                // Copy zip input to output
                CopyUtils.copy(zipInput, zipOutput);
            } catch (Exception zex) {
                // ignore it
            } finally {
                zipInput.closeEntry();
                zipOutput.closeEntry();
            }
        }
    } finally {
        if (zipInput != null) {
            try {
                zipInput.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

public void _unzipArchive(File archive, File outputDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(archive);
    CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
    ZipEntry entry;/* www  . j a  v a 2  s .c  om*/
    while ((entry = zis.getNextEntry()) != null) {
        log.debug("Extracting: " + entry);
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(entry.getName());
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
    log.debug("Checksum:" + checksum.getChecksum().getValue());

}

From source file:de.uka.ilkd.key.dl.gui.initialdialog.gui.ToolInstaller.java

/**
 * @param tmp//from   ww  w  .  j a va  2s.com
 * @param
 * @throws FileNotFoundException
 * @throws IOException
 */
private static void unzip(File file, File dir, PropertySetter ps, JProgressBar bar)
        throws FileNotFoundException, IOException {
    final int BUFFER = 2048;
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(file);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    int value = 0;
    while ((entry = zis.getNextEntry()) != null) {
        bar.setValue(value++);
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        String outputFile = dir.getAbsolutePath() + File.separator + entry.getName();
        if (entry.isDirectory()) {
            new File(outputFile).mkdirs();
        } else {
            FileOutputStream fos = new FileOutputStream(outputFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
            File oFile = new File(outputFile);
            if (OSInfosDefault.INSTANCE.getOs() == OperatingSystem.OSX) {
                // FIXME: we need to make everything executable as somehow
                // the executable bit is not preserved in
                // OSX
                oFile.setExecutable(true);
            }
            if (ps.filterFilename(oFile)) {
                ps.setProperty(outputFile);
            }
        }
    }
    zis.close();
    file.delete();
}

From source file:org.docx4j.openpackaging.io3.stores.ZipPartStore.java

public ZipPartStore(InputStream is) throws Docx4JException {

    partByteArrays = new HashMap<String, ByteArray>();
    try {//from  w  ww. j  av a 2  s  . co  m
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            byte[] bytes = getBytesFromInputStream(zis);
            //log.debug("Extracting " + entry.getName());
            partByteArrays.put(entry.getName(), new ByteArray(bytes));
        }
        zis.close();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new Docx4JException("Error processing zip file (is it a zip file?)", e);
    }

}

From source file:com.comcast.magicwand.spells.web.chrome.ChromePhoenixDriver.java

private void extractZip(File sourceZipFile, String destinationDir) throws IOException {
    LOG.debug("Extracting [{}] to dir [{}]", sourceZipFile, destinationDir);
    ZipInputStream zis = null;
    ZipEntry entry;//  www  .  j a  va  2 s .  c o m

    try {
        zis = new ZipInputStream(FileUtils.openInputStream(sourceZipFile));

        while (null != (entry = zis.getNextEntry())) {
            File dst = Paths.get(destinationDir, entry.getName()).toFile();

            FileOutputStream output = FileUtils.openOutputStream(dst);
            try {
                IOUtils.copy(zis, output);
                output.close();
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
        zis.close();
    } finally {
        IOUtils.closeQuietly(zis);
    }
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * unZip Archive//www  .ja v  a 2  s  .  co  m
 *
 * @param zipFilePath  input zip file
 * @param outputFolder zip file output folder
 */
protected static void unZipArchive(GenerationLogger GENERATION_LOGGER, String zipFilePath, String outputFolder)
        throws IOException {
    /**
     * Create Output Directory, but should already Exist.
     */
    File folder = new File(outputFolder);
    if (!folder.exists()) {
        folder.mkdir();
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = outputFolder + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(GENERATION_LOGGER, zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

protected void processZipFileItem(FileItemFactory factory, FileItem zip, List<FileItem> fileItems)
        throws IOException {
    ZipInputStream ziS = new ZipInputStream(zip.getInputStream());
    ZipEntry zE;/*  www . j ava2  s  . com*/
    try {
        while (null != (zE = ziS.getNextEntry())) {
            if (zE.isDirectory() || !uploadFileNameFilter.accept(null, zE.getName()))
                continue;
            FileItem item = factory.createItem(null, null, false, zE.getName());
            OutputStream oS = item.getOutputStream();
            IOUtils.copyLarge(ziS, oS);
            oS.close();
            fileItems.add(item);
        }
    } finally {
        ziS.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 ww  w.  ja va 2s.co  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:org.apache.solr.handler.admin.ConfigSetsHandler.java

private void handleConfigUploadRequest(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    String configSetName = req.getParams().get(NAME);
    if (StringUtils.isBlank(configSetName)) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "The configuration name should be provided in the \"name\" parameter");
    }// w  w  w .  ja  va2  s. c  om

    SolrZkClient zkClient = coreContainer.getZkController().getZkClient();
    String configPathInZk = ZkConfigManager.CONFIGS_ZKNODE + Path.SEPARATOR + configSetName;

    if (zkClient.exists(configPathInZk, true)) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "The configuration " + configSetName + " already exists in zookeeper");
    }

    Iterator<ContentStream> contentStreamsIterator = req.getContentStreams().iterator();

    if (!contentStreamsIterator.hasNext()) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "No stream found for the config data to be uploaded");
    }

    InputStream inputStream = contentStreamsIterator.next().getStream();

    // Create a node for the configuration in zookeeper
    boolean trusted = getTrusted(req);
    zkClient.makePath(configPathInZk,
            ("{\"trusted\": " + Boolean.toString(trusted) + "}").getBytes(StandardCharsets.UTF_8), true);

    ZipInputStream zis = new ZipInputStream(inputStream, StandardCharsets.UTF_8);
    ZipEntry zipEntry = null;
    while ((zipEntry = zis.getNextEntry()) != null) {
        String filePathInZk = configPathInZk + "/" + zipEntry.getName();
        if (zipEntry.isDirectory()) {
            zkClient.makePath(filePathInZk, true);
        } else {
            createZkNodeIfNotExistsAndSetData(zkClient, filePathInZk, IOUtils.toByteArray(zis));
        }
    }
    zis.close();
}

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Extract zip archive stream into the target directory
 * @param targetDirectory$ the path of the target directory
 * @param zis the zip archive input stream.
 *//*from   w w w.ja v  a 2  s.  c  om*/
public static void extractEntitiesFromZip(String targetDirectory$, ZipInputStream zis) {
    try {
        ZipEntry entry = null;
        File outputFile;
        File outputDir;
        FileOutputStream outputStream;
        while ((entry = zis.getNextEntry()) != null) {
            outputFile = new File(targetDirectory$ + "/" + entry.getName());
            outputDir = outputFile.getParentFile();
            if (!outputDir.exists())
                outputDir.mkdirs();
            if (entry.isDirectory()) {
                outputFile.mkdir();
            } else {
                outputStream = new FileOutputStream(outputFile);
                IOUtils.copy(zis, outputStream);
                outputStream.close();
            }
        }
        zis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}