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.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
 **//  www  .j a  v a  2s  .c  o m
 ** Method:   locateMetadata()
 ** Input:  String zipFileName  --  The name of the zip file to be used
 ** Output: Vector  --  A vector of the names of xml files.  
 **
 ** Description: This method takes in the name of a zip file and locates 
 **              all files with an .xml extension an adds their names to a 
 **              vector. 
 **              
 *****************************************************************************/
public static Vector locateMetadata(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in locateMetadata()    ");
        System.out.println("***********************\n");
    }

    //  An array of names of xml files to be returned to ColdFusion
    Vector metaDataVector = new Vector();
    String suffix = ".xml";

    try {
        //  The zip file being searched.
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        //  An entry in the zip file
        ZipEntry entry;

        if (_Debug) {
            System.out.println("Other meta-data located:");
        }
        while ((in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).endsWith(suffix)) {
                    if (_Debug) {
                        System.out.println(entry.getName());
                    }
                    metaDataVector.addElement(entry.getName());
                }
            }
        }
        in.close();

    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
    }
    return metaDataVector;
}

From source file:org.fusesource.ide.foundation.ui.archetypes.ArchetypeHelper.java

public static Map<String, String> getArchetypeRequiredProperties(URL jarURL)
        throws IOException, XPathExpressionException, ParserConfigurationException, SAXException {
    ZipInputStream zis = new ZipInputStream(jarURL.openStream());
    try {//from w  w  w.  j  a  v  a  2 s  . c  o m
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            try {
                if (!entry.isDirectory() && "META-INF/maven/archetype-metadata.xml".equals(entry.getName())) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    copy(zis, bos);
                    bos.flush();
                    return getArchetypeRequiredProperties(bos, true, true);
                }
            } finally {
                zis.closeEntry();
            }
        }
    } finally {
        zis.close();
    }
    return Collections.EMPTY_MAP;
}

From source file:de.uni_hildesheim.sse.ant.versionReplacement.PluginVersionReplacer.java

/**
 * Unpacks an existing JAR/Zip archive./*from  w ww .ja  va2  s. c o m*/
 * 
 * @param zipFile The Archive file to unzip.
 * @param outputFolder The destination folder where the unzipped content shall be saved.
 * @see <a href="http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/">
 * http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/</a>
 */
private static void unZipIt(File zipFile, File outputFolder) {

    byte[] buffer = new byte[1024];

    try {

        // create output directory is not exists
        File folder = outputFolder;
        if (folder.exists()) {
            FileUtils.deleteDirectory(folder);
        }
        folder.mkdir();

        // get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder, fileName);

            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            if (!ze.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(newFile);

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

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

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.baasbox.controllers.Root.java

/**
 * /admin/db/import (POST)//from   w w w. j  ava 2s  .c o m
 * 
 * the method allows to upload a json export file and apply it to the db.
 * WARNING: all data on the db will be wiped out before importing
 * 
 * @return a 200 Status code when the import is successfull,a 500 status code otherwise
 */
@With({ RootCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result importDb() {
    String appcode = (String) ctx().args.get("appcode");
    MultipartFormData body = request().body().asMultipartFormData();
    if (body == null)
        return badRequest("missing data: is the body multipart/form-data?");
    FilePart fp = body.getFile("file");

    if (fp != null) {
        ZipInputStream zis = null;
        try {
            java.io.File multipartFile = fp.getFile();
            java.util.UUID uuid = java.util.UUID.randomUUID();
            File zipFile = File.createTempFile(uuid.toString(), ".zip");
            FileUtils.copyFile(multipartFile, zipFile);
            zis = new ZipInputStream(new FileInputStream(zipFile));
            DbManagerService.importDb(appcode, zis);
            zipFile.delete();
            return ok();
        } catch (Exception e) {
            BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
            return internalServerError(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (zis != null) {
                    zis.close();
                }
            } catch (IOException e) {
                // Nothing to do here
            }
        }
    } else {
        return badRequest("The form was submitted without a multipart file field.");
    }
}

From source file:org.deeplearning4j.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to/*from   ww  w  .  j  a  va 2 s  . com*/
 * @param dest the destination directory
 * @throws 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);

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

            //createComplex all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

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

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

        zis.closeEntry();
        zis.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();
    }

    target.delete();

}

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  .  j a v  a 2s  .  co 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:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Unzips the files from a zipfile into a directory. All of the files will be put in a single
 * direcotry. If the zipfile contains a hierarchycal structure, it will be ignored.
 * //from www . j ava  2 s  . c  o  m
 * @param zipFile
 *            The zipfile to be examined
 * @param destDir
 *            The direcotry where the extracted files will be stored.
 * @return The list of the extracted files, or null if an error occurred.
 * @throws IllegalArgumentException
 *             if the destination dir is not writeable.
 * @deprecated use Extractor.unZip instead which support complex zip structure
 */
public static List<File> unzipFlat(final File zipFile, final File destDir) {
    // if (!destDir.isDirectory())
    // throw new IllegalArgumentException("Not a directory '" + destDir.getAbsolutePath()
    // + "'");

    if (!destDir.canWrite())
        throw new IllegalArgumentException("Unwritable directory '" + destDir.getAbsolutePath() + "'");

    try {
        List<File> ret = new ArrayList<File>();
        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));

        for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
                .getNextEntry()) {
            String entryName = zipentry.getName();
            if (zipentry.isDirectory())
                continue;

            File outFile = new File(destDir, entryName);
            ret.add(outFile);
            FileOutputStream fileoutputstream = new FileOutputStream(outFile);

            org.apache.commons.io.IOUtils.copy(zipinputstream, fileoutputstream);
            fileoutputstream.close();
            zipinputstream.closeEntry();
        }

        zipinputstream.close();
        return ret;
    } catch (Exception e) {
        LOGGER.warn("Error unzipping file '" + zipFile.getAbsolutePath() + "'", e);
        return null;
    }
}

From source file:org.bml.util.CompressUtils.java

/**
 * Extracts a zip | jar | war archive to the specified directory.
 * Uses the passed buffer size for read operations.
 *
 * @param zipFile/*from   w  ww  .jav  a 2 s .  co m*/
 * @param destDir
 * @param bufferSize
 * @throws IOException If there is an issue with the archive file or the file system.
 * @throws NullPointerException if any of the arguments are null.
 * @throws IllegalArgumentException if any of the arguments do not pass the
 * preconditions other than null tests. NOTE: This exception wil not be thrown
 * if this classes CHECKED member is set to false
 *
 * @pre zipFile!=null
 * @pre zipFile.exists()
 * @pre zipFile.canRead()
 * @pre zipFile.getName().matches("(.*[zZ][iI][pP])|(.*[jJ][aA][rR])")
 *
 * @pre destDir!=null
 * @pre destDir.exists()
 * @pre destDir.isDirectory()
 * @pre destDir.canWrite()
 *
 * @pre bufferSize > 0
 */
public static void unzipFilesToPath(final File zipFile, final File destDir, final int bufferSize)
        throws IOException, IllegalArgumentException, NullPointerException {

    //zipFilePath.toLowerCase().endsWith(zipFilePath)
    if (CHECKED) {
        final String userName = User.getSystemUserName();//use cahced if possible
        //zipFile
        Preconditions.checkNotNull(zipFile, "Can not unzip null zipFile");
        Preconditions.checkArgument(zipFile.getName().matches(ZIP_MIME_PATTERN),
                "Zip File at %s does not match the extensions allowed by the regex %s", zipFile,
                ZIP_MIME_PATTERN);
        Preconditions.checkArgument(zipFile.exists(), "Can not unzip file at %s. It does not exist.", zipFile);
        Preconditions.checkArgument(zipFile.canRead(),
                "Can not extract archive with no read permissions. Check File permissions. USER=%s FILE=%s",
                System.getProperty("user.name"), zipFile);
        //destDir
        Preconditions.checkNotNull(destDir, "Can not extract zipFileName=%s to a null destination", zipFile);
        Preconditions.checkArgument(destDir.isDirectory(),
                "Can not extract zipFileName %s to a destination %s that is not a directory", zipFile, destDir);
        Preconditions.checkArgument(destDir.exists(),
                "Can not extract zipFileName %s to a non existant destination %s", zipFile, destDir);
        Preconditions.checkArgument(destDir.canWrite(),
                "Can not extract archive with no write permissions. Check File permissions. USER=%s FILE=%s",
                System.getProperty("user.name"), destDir);
        //bufferSize
        Preconditions.checkArgument(bufferSize > 0,
                "Can not extract archive %s to %s with a buffer size less than 1 size = %s", zipFile, destDir,
                bufferSize);

    }

    final FileInputStream fileInputStream = new FileInputStream(zipFile);
    final ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
    final String destBasePath = destDir.getAbsolutePath() + PATH_SEP;

    try {
        ZipEntry zipEntry;
        BufferedOutputStream destBufferedOutputStream;
        int byteCount;
        byte[] data;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            destBufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(destBasePath + zipEntry.getName()), bufferSize);
            data = new byte[bufferSize];
            while ((byteCount = zipInputStream.read(data, 0, bufferSize)) != -1) {
                destBufferedOutputStream.write(data, 0, byteCount);
            }
            destBufferedOutputStream.flush();
            destBufferedOutputStream.close();
        }
        fileInputStream.close();
        zipInputStream.close();
    } catch (IOException ioe) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(String.format("IOException caught while unziping archive %s to %s", zipFile, destDir),
                    ioe);
        }
        throw ioe;
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:com.ariatemplates.attester.maven.ArtifactExtractor.java

public static void unzip(File zipFile, File outputFolder) throws IOException {
    ZipInputStream zipInputStream = null;
    try {/* w  w  w  .j ava 2s . co  m*/
        ZipEntry entry = null;
        zipInputStream = new ZipInputStream(FileUtils.openInputStream(zipFile));
        while ((entry = zipInputStream.getNextEntry()) != null) {
            File outputFile = new File(outputFolder, entry.getName());

            if (entry.isDirectory()) {
                outputFile.mkdirs();
                continue;
            }

            OutputStream outputStream = null;
            try {
                outputStream = FileUtils.openOutputStream(outputFile);
                IOUtils.copy(zipInputStream, outputStream);
                outputStream.close();
            } catch (IOException exception) {
                outputFile.delete();
                throw new IOException(exception);
            } finally {
                IOUtils.closeQuietly(outputStream);
            }
        }
        zipInputStream.close();
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:org.cirdles.webServices.calamari.PrawnFileHandlerService.java

public static String extract(File inFile, File destination) throws IOException {
    File outFile = null;//from w w w .  ja v  a2  s . c  o m
    OutputStream out = null;
    ZipInputStream zis = null;

    try {
        //open infile for reading
        zis = new ZipInputStream(new FileInputStream(inFile));
        ZipEntry entry = null;

        //checks first entry exists
        if ((entry = zis.getNextEntry()) != null) {
            String outFilename = entry.getName();
            outFile = new File(destination, outFilename);

            try {
                //open outFile for writing
                out = new FileOutputStream(outFile);
                byte[] buff = new byte[2048];
                int len = 0;

                while ((len = zis.read(buff)) > 0) {
                    out.write(buff, 0, len);
                }
            }

            finally {
                //close outFile
                if (out != null)
                    out.close();
            }
        }
    } finally {
        //close zip file
        if (zis != null)
            zis.close();
    }

    return outFile.getPath();

}