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:org.datavec.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to// w  w  w  . j  a  v  a  2  s  .  c  o m
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip") || file.endsWith(".jar")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static void unzip(String sourceFile, String destDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(sourceFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry = null;//w w  w.  j a va2s .  c  o m

    int BUFFER_SIZE = 4096;
    while ((entry = zis.getNextEntry()) != null) {
        String dst = destDir + File.separator + entry.getName();
        if (entry.isDirectory()) {
            createDir(destDir, entry);
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];

        // write the file to the disk
        FileOutputStream fos = new FileOutputStream(dst);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        // close the output streams
        dest.flush();
        dest.close();
    }

    zis.close();
}

From source file:org.canova.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to/* w  w w  .j a v a  2 s.  co m*/
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

From source file:com.ikanow.aleph2.analytics.storm.utils.TestStormControllerUtil_Cache.java

private long getFileModifiedTime(File input_jar) throws IOException {
    ZipInputStream inputZip = new ZipInputStream(new FileInputStream(input_jar));
    ZipEntry e = inputZip.getNextEntry();
    long time = e.getLastModifiedTime().toMillis();
    inputZip.close();
    return time;//  ww w  . j  a  v a2 s . c o m
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static String getShapefileNameFromCompressed(InputStream is) {
    String shapefileName = null;/*from   ww w .ja  va2  s.c  om*/
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry ze;
    try {
        while (((ze = zis.getNextEntry()) != null) && (shapefileName == null)) {
            if (!ze.isDirectory()) {
                String fileName = ze.getName().toLowerCase();
                if (fileName.endsWith(".shp")) {
                    shapefileName = fileName;
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            zis.closeEntry();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            zis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return shapefileName;
}

From source file:name.martingeisse.webide.plugin.PluginBundleWicketResource.java

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {

    // fetch the JAR file
    final SQLQuery query = EntityConnectionManager.getConnection().createQuery();
    query.from(QPluginBundles.pluginBundles);
    query.where(QPluginBundles.pluginBundles.id.eq(pluginBundleId));
    final Object[] row = (Object[]) (Object) query.singleResult(QPluginBundles.pluginBundles.jarfile);
    final byte[] jarData = (byte[]) row[0];
    String matchingEntryName;/*from   www.ja  v a 2 s  . com*/
    final byte[] matchingEntryData;

    // if requested, load a single file from the JAR
    if (localPath != null) {
        final String localPathText = localPath.withLeadingSeparator(false).withTrailingSeparator(false)
                .toString();
        try {
            final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(jarData));
            while (true) {
                final ZipEntry entry = zipInputStream.getNextEntry();
                if (entry == null) {
                    zipInputStream.close();
                    final ResourceResponse response = new ResourceResponse();
                    response.setError(404, "Plugin bundle (id " + pluginBundleId + ") does not contain file: "
                            + localPathText);
                    response.setStatusCode(404);
                    return response;
                }
                if (localPathText.equals(entry.getName())) {
                    matchingEntryName = entry.getName();
                    matchingEntryData = IOUtils.toByteArray(zipInputStream);
                    zipInputStream.close();
                    break;
                }
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        matchingEntryName = null;
        matchingEntryData = null;
    }

    // build the response
    final ResourceResponse response = new ResourceResponse();
    response.setCacheDuration(Duration.NONE);
    response.setContentDisposition(ContentDisposition.ATTACHMENT);
    if (matchingEntryData == null) {
        response.setFileName("plugin-bundle-" + pluginBundleId + ".jar");
    } else {
        final int lastSlashIndex = matchingEntryName.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            matchingEntryName = matchingEntryName.substring(lastSlashIndex + 1);
        }
        response.setFileName(matchingEntryName);
    }
    response.setWriteCallback(new WriteCallback() {
        @Override
        public void writeData(final Attributes attributes) throws IOException {
            attributes.getResponse().write(matchingEntryData == null ? jarData : matchingEntryData);
        }
    });
    return response;

}

From source file:com.netsteadfast.greenstep.util.BusinessProcessManagementUtils.java

public static String deployment(SysBpmnResourceVO sysBpmnResource) throws ServiceException, Exception {
    DefaultResult<SysBpmnResourceVO> result = sysBpmnResourceService.findByUK(sysBpmnResource);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }//from  ww w .j ava 2s . c  om
    ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(result.getValue().getContent()));
    Deployment deployment = null;
    try {
        deployment = repositoryService.createDeployment().name(result.getValue().getName())
                .addZipInputStream(zip).deploy();
        result.getValue().setDeploymentId(deployment.getId());
        byte[] content = result.getValue().getContent();
        result.getValue().setContent(null); // content
        sysBpmnResourceService.updateObject(result.getValue()); // content
        result.getValue().setContent(content); // content
        sysBpmnResourceService.updateObject(result.getValue()); // content   
        logger.info("deployment Id: " + deployment.getId() + " , name: " + deployment.getName());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage().toString());
        throw e;
    } finally {
        zip.close();
        zip = null;
    }
    return deployment.getId();
}

From source file:org.apache.hive.beeline.ClassNameCompleter.java

/**
 * Get clazz names from a jar file path//from   ww w  .  j av  a2s  .  com
 * @param path specifies the jar file's path
 * @return
 */
private static List<String> getClassNamesFromJar(String path) {
    List<String> classNames = new ArrayList<String>();
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(new FileInputStream(path));
        ZipEntry entry = zip.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory() && entry.getName().endsWith(clazzFileNameExtension)) {
                StringBuilder className = new StringBuilder();
                for (String part : entry.getName().split("/")) {
                    if (className.length() != 0) {
                        className.append(".");
                    }
                    className.append(part);
                    if (part.endsWith(clazzFileNameExtension)) {
                        className.setLength(className.length() - clazzFileNameExtension.length());
                    }
                }
                classNames.add(className.toString());
            }
            entry = zip.getNextEntry();
        }
    } catch (IOException e) {
        LOG.error("Fail to parse the class name from the Jar file due to the exception:" + e);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                LOG.error("Fail to close the file due to the exception:" + e);
            }
        }
    }

    return classNames;
}

From source file:com.nuvolect.deepdive.probe.ApkZipUtil.java

/**
 * Unzip while excluding XML files into the target directory.
 * The added structure is updated to reflect any new files and directories created.
 * Overwrite files when requested./*  w  ww .  j ava2 s . c o m*/
 * @param zipOmni
 * @param targetDir
 * @param progressStream
 * @return
 */
public static boolean unzipAllExceptXML(OmniFile zipOmni, OmniFile targetDir, ProgressStream progressStream) {

    String volumeId = zipOmni.getVolumeId();
    String rootFolderPath = targetDir.getPath();
    boolean DEBUG = true;

    ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream());
    ZipEntry entry = null;
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (entry.isDirectory()) {

                OmniFile dir = new OmniFile(volumeId, entry.getName());
                if (dir.mkdir()) {

                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "dir created: " + dir.getPath());
                }
            } else {

                String path = rootFolderPath + "/" + entry.getName();
                OmniFile file = new OmniFile(volumeId, path);

                if (!FilenameUtils.getExtension(file.getName()).contentEquals("xml")) {

                    // Create any necessary directories
                    file.getParentFile().mkdirs();

                    OutputStream out = file.getOutputStream();

                    OmniFiles.copyFileLeaveInOpen(zis, out);
                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "file created: " + file.getPath());

                    progressStream.putStream("Unpacked: " + entry.getName());
                }
            }
        }
        zis.close();

    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        return false;
    }

    return true;
}

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

/**
 * Extract the given ZIP file into the given destination folder.
 * /*from ww  w.  j  av a  2  s. c  o m*/
 * @param zipFile
 *            file to extract
 *            
 * @param baseFolder
 *            destination folder to extract in
 */
public static void extractZipToFolder(File zipFile, File baseFolder) {
    try {
        byte[] buf = new byte[1024];

        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            // for each entry to be extracted
            String entryName = zipentry.getName();

            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);

            int numBytes;
            FileOutputStream fileoutputstream;
            File newFile = new File(baseFolder, entryName);
            if (zipentry.isDirectory()) {
                if (!newFile.mkdirs()) {
                    break;
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            fileoutputstream = new FileOutputStream(newFile);
            while ((numBytes = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, numBytes);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}