Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:fll.web.admin.UploadSubjectiveData.java

/**
 * Save the data stored in file to the database and update the subjective
 * score totals./* w  w w  .  j  a  v  a 2  s . c  o  m*/
 * 
 * @param file the file to read the data from
 * @param connection the database connection to write to
 * @throws SAXException if there is an error parsing the document
 */
public static void saveSubjectiveData(final File file, final int currentTournament,
        final ChallengeDescription challengeDescription, final Connection connection,
        final ServletContext application) throws SQLException, IOException, ParseException, SAXException {
    if (LOGGER.isDebugEnabled()) {
        try {
            LOGGER.debug("Saving uploaded file to ");
            final String baseFilename = "subjective-upload_" + DATE_TIME_FORMAT.get().format(new Date());
            final String filename = application.getRealPath("/WEB-INF/" + baseFilename);

            final File copy = new File(filename);
            FileOutputStream output = null;
            FileInputStream input = null;
            try {
                input = new FileInputStream(file);
                output = new FileOutputStream(copy);
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        } catch (final IOException e) {
            LOGGER.debug("Error creating copy of subjective datafile", e);
        }
    }
    ZipFile zipfile = null;
    Document scoreDocument = null;
    try {
        try {
            zipfile = new ZipFile(file);

            // read in score data
            final ZipEntry scoreZipEntry = zipfile.getEntry("score.xml");
            if (null == scoreZipEntry) {
                throw new RuntimeException("Zipfile does not contain score.xml as expected");
            }
            final InputStream scoreStream = zipfile.getInputStream(scoreZipEntry);
            scoreDocument = XMLUtils.parseXMLDocument(scoreStream);
            scoreStream.close();
            zipfile.close();

        } catch (final ZipException ze) {
            LOGGER.info("Subjective upload is not a zip file, trying as an XML file");

            // not a zip file, parse as just the XML file
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                scoreDocument = XMLUtils.parseXMLDocument(fis);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

        if (null == scoreDocument) {
            throw new FLLRuntimeException(
                    "Cannot parse input as a compressed subjective data file or an uncompressed XML file");
        }

        saveSubjectiveData(scoreDocument, currentTournament, challengeDescription, connection);
    } finally {
        if (null != zipfile) {
            zipfile.close();
        }
    }
}

From source file:com.ts.db.connector.ConnectorDriverManager.java

private static Driver getDriver(File jar, String url, ClassLoader cl) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {//  w w w . ja v a2s  .c  o m
        for (ZipEntry entry : Iteration.asIterable(zipFile.entries())) {
            final String name = entry.getName();
            if (name.endsWith(".class")) {
                final String fqcn = name.replaceFirst("\\.class", "").replace('/', '.');
                try {
                    Class<?> c = DynamicLoader.loadClass(fqcn, cl);
                    if (Driver.class.isAssignableFrom(c)) {
                        Driver driver = (Driver) c.newInstance();
                        if (driver.acceptsURL(url)) {
                            return driver;
                        }
                    }
                } catch (Exception ex) {
                    if (log.isTraceEnabled()) {
                        log.trace(ex.toString());
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
    return null;
}

From source file:com.mc.printer.model.utils.ZipHelper.java

public static void unZip(String sourceZip, String outDirName) throws IOException {
    log.info("unzip source:" + sourceZip);
    log.info("unzip to :" + outDirName);
    ZipFile zfile = new ZipFile(sourceZip);
    System.out.println(zfile.getName());
    Enumeration zList = zfile.entries();
    ZipEntry ze = null;//from w  w w . jav  a 2  s  .  c om
    byte[] buf = new byte[1024];
    while (zList.hasMoreElements()) {
        //ZipFileZipEntry
        ze = (ZipEntry) zList.nextElement();
        if (ze.isDirectory()) {
            continue;
        }
        //ZipEntry?InputStreamOutputStream
        File fil = getRealFileName(outDirName, ze.getName());

        OutputStream os = new BufferedOutputStream(new FileOutputStream(fil));
        InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
        int readLen = 0;
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            os.write(buf, 0, readLen);
        }
        is.close();
        os.close();
        log.debug("Extracted: " + ze.getName());
    }
    zfile.close();

}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given archive into the given destination directory
 * /*  ww  w.j av  a2  s .com*/
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws Exception
 */
public static void extractArchive(File archive, File destDir) throws IOException {

    if (!destDir.exists()) {
        destDir.mkdir();
    }

    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    byte[] buffer = new byte[16384];
    int len;
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        String entryFileName = entry.getName();

        File dir = buildDirectoryHierarchyFor(entryFileName, destDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {

            File file = new File(destDir, entryFileName);

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

            while ((len = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }

            bos.flush();
            bos.close();
            bis.close();
        }
    }
    zipFile.close();
}

From source file:it.mb.whatshare.Dialogs.java

private static String getBuildDate(final Activity activity) {
    String buildDate = "";
    ZipFile zf = null;
    try {//from   w w  w  . j  a v  a  2 s  . co m
        ApplicationInfo ai = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), 0);
        zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        buildDate = SimpleDateFormat.getInstance().format(new java.util.Date(time));

    } catch (Exception e) {
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return buildDate;
}

From source file:it.geosolutions.geofence.gui.server.utility.IoUtility.java

/**
 * Decompress.//from  ww w . j  a  v a2  s  .com
 *
 * @param prefix
 *            the prefix
 * @param inputFile
 *            the input file
 * @param tempFile
 *            the temp file
 * @return the file
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static File decompress(final String prefix, final File inputFile, final File tempFile)
        throws IOException {
    final File tmpDestDir = createTodayPrefixedDirectory(prefix, new File(tempFile.getParent()));

    ZipFile zipFile = new ZipFile(inputFile);

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {

        ZipEntry entry = (ZipEntry) entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);

        if (entry.isDirectory()) {
            // Assume directories are stored parents first then
            // children.
            (new File(tmpDestDir, entry.getName())).mkdir();

            continue;
        }

        File newFile = new File(tmpDestDir, entry.getName());

        FileOutputStream fos = new FileOutputStream(newFile);
        try {
            byte[] buf = new byte[1024];
            int len;

            while ((len = stream.read(buf)) >= 0) {
                saveCompressedStream(buf, fos, len);
            }

        } catch (IOException e) {
            zipFile.close();

            IOException ioe = new IOException("Not valid ZIP archive file type.");
            ioe.initCause(e);
            throw ioe;
        } finally {
            fos.flush();
            fos.close();

            stream.close();
        }
    }
    zipFile.close();

    if ((tmpDestDir.listFiles().length == 1) && (tmpDestDir.listFiles()[0].isDirectory())) {
        return getShpFile(tmpDestDir.listFiles()[0]);
    }

    // File[] files = tmpDestDir.listFiles(new FilenameFilter() {
    //
    // public boolean accept(File dir, String name) {
    // return FilenameUtils.getExtension(name).equalsIgnoreCase("shp");
    // }
    // });
    //
    // return files.length > 0 ? files[0] : null;

    return getShpFile(tmpDestDir);
}

From source file:org.wso2.carbon.appfactory.jenkins.artifact.storage.Utils.java

/**
 * Unzip a zipfile to a destination specified. N
 *
 * @param zipFilename//from  w ww. jav a  2  s.c o m
 *            input zip file
 * @param destDirname
 *            destination directory
 * @throws IOException
 *             an error
 */

public static void unzip(String zipFilename, String destDirname) throws IOException {

    File distinationDir = new File(destDirname);
    if (!distinationDir.isDirectory()) {

        if (!distinationDir.mkdirs()) {

            throw new IOException("Unable to create output directory :" + distinationDir);

        }
    }

    ZipFile zipFile = new ZipFile(zipFilename);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(distinationDir, entry.getName());
            if (!entry.isDirectory()) {
                entryDestination.getParentFile().mkdirs(); // TO ensure that parent path already exists.
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);

            } else {
                if (!entryDestination.mkdirs()) {
                    log.warn("Couldn't create the directory :" + entryDestination.getAbsolutePath());
                }
            }
        }

    } finally {
        zipFile.close();
    }

}

From source file:dk.netarkivet.common.utils.ZipUtils.java

/** Unzip a zipFile into a directory.  This will create subdirectories
 * as needed./*ww w  . j a va  2  s  .c o m*/
 *
 * @param zipFile The file to unzip
 * @param toDir The directory to create the files under.  This directory
 * will be created if necessary.  Files in it will be overwritten if the
 * filenames match.
 */
public static void unzip(File zipFile, File toDir) {
    ArgumentNotValid.checkNotNull(zipFile, "File zipFile");
    ArgumentNotValid.checkNotNull(toDir, "File toDir");
    ArgumentNotValid.checkTrue(toDir.getAbsoluteFile().getParentFile().canWrite(),
            "can't write to '" + toDir + "'");
    ArgumentNotValid.checkTrue(zipFile.canRead(), "can't read '" + zipFile + "'");
    InputStream inputStream = null;
    ZipFile unzipper = null;
    try {
        try {
            unzipper = new ZipFile(zipFile);
            Enumeration<? extends ZipEntry> entries = unzipper.entries();
            while (entries.hasMoreElements()) {
                ZipEntry ze = entries.nextElement();
                File target = new File(toDir, ze.getName());
                // Ensure that its dir exists
                FileUtils.createDir(target.getCanonicalFile().getParentFile());
                if (ze.isDirectory()) {
                    target.mkdir();
                } else {
                    inputStream = unzipper.getInputStream(ze);
                    FileUtils.writeStreamToFile(inputStream, target);
                    inputStream.close();
                }
            }
        } finally {
            if (unzipper != null) {
                unzipper.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Failed to unzip '" + zipFile + "'", e);
    }
}

From source file:org.sonatype.nexus.unpack.rest.UnpackPlexusResource.java

private void close(final ZipFile zip) {
    try {/*ww w .ja  v  a 2 s .c  o  m*/
        zip.close();
    } catch (IOException e) {
        getLogger().debug("Could not close ZipFile", e);
    }
}

From source file:com.chinamobile.bcbsp.fault.tools.Zip.java

/**
 * Uncompress *.zip files.//from w w w  .j  a  v  a  2s  .c  o  m
 * @param fileName
 *        : file to be uncompress
 */
@SuppressWarnings("unchecked")
public static void decompress(String fileName) {
    File sourceFile = new File(fileName);
    String filePath = sourceFile.getParent() + "/";
    try {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration en = zipFile.entries();
        byte[] data = new byte[BUFFER];
        while (en.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bis.close();
            bos.close();
        }
        zipFile.close();
    } catch (IOException e) {
        //LOG.error("[compress]", e);
        throw new RuntimeException("[compress]", e);
    }
}