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:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Deserializes examplars stored in archives in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getArchiveDirectory()/*  w  w w  . j av  a 2  s.c om*/
 */
public void deserializeArchivedVersions() throws RuntimeException {
    System.out.println("Deserializing archived instances in " + getArchiveDirectory() + ".");

    File archive = new File(getArchiveDirectory());

    if (!archive.exists() || !archive.isDirectory()) {
        return;
    }

    String[] listing = archive.list();

    for (String archiveName : listing) {
        if (!(archiveName.endsWith(".zip"))) {
            continue;
        }

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            ZipFile zipFile = new ZipFile(file);
            ZipEntry entry = zipFile.getEntry("class_fields.ser");
            InputStream inputStream = zipFile.getInputStream(entry);
            ObjectInputStream objectIn = new ObjectInputStream(inputStream);
            Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject();
            zipFile.close();

            for (String className : classFields.keySet()) {

                //                    if (classFields.equals("HypotheticalGraph")) continue;

                List<String> fieldNames = classFields.get(className);
                Class<?> clazz = Class.forName(className);
                ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);

                if (streamClass == null) {
                    System.out.println();
                }

                for (String fieldName : fieldNames) {
                    assert streamClass != null;
                    ObjectStreamField field = streamClass.getField(fieldName);

                    if (field == null) {
                        throw new RuntimeException("Field '" + fieldName + "' was dropped from class '"
                                + className + "' as a serializable field! Please " + "put it back!!!"
                                + "\nIt used to be in " + className + " in this archive: " + archiveName + ".");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }

        System.out.println("...Deserializing instances in " + archiveName + "...");
        ZipEntry zipEntry = null;

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            FileInputStream in = new FileInputStream(file);
            ZipInputStream zipinputstream = new ZipInputStream(in);

            while ((zipEntry = zipinputstream.getNextEntry()) != null) {
                if (!zipEntry.getName().endsWith(".ser")) {
                    continue;
                }

                ObjectInputStream objectIn = new ObjectInputStream(zipinputstream);
                objectIn.readObject();
                zipinputstream.closeEntry();
            }

            zipinputstream.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName
                            + ". " + "Perhaps the class was renamed, moved to another package, or "
                            + "removed. In any case, please put it back where it was.",
                    e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }
    }

    System.out.println("Finished deserializing archived instances.");
}

From source file:io.github.jeremgamer.preview.actions.Launch.java

private void extractNatives() throws IOException {
    for (String s : NATIVE_JARS) {
        File archive = new File(s);
        ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(VANILLA_NATIVE_DIR.replaceAll("<version>", "1.8.1"),
                    entry.getName());/*from   ww  w .  j  ava 2s .  c  o  m*/
            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                in.close();
                out.close();
            }
        }
        zipFile.close();
    }
}

From source file:org.apache.slider.common.tools.CoreFileSystem.java

/**
 * Verify that a file exists in the zip file given by path
 * @param path path to zip file/*from ww w  .j  a v a2 s.  c om*/
 * @param file file expected to be in zip
 * @throws FileNotFoundException file not found or is not a zip file
 * @throws IOException  trouble with FS
 */
public void verifyFileExistsInZip(Path path, String file) throws IOException {
    fileSystem.copyToLocalFile(path, new Path("/tmp"));
    File dst = new File((new Path("/tmp", path.getName())).toString());
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile = new ZipFile(dst);
    boolean found = false;

    try {
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String nm = entry.getName();
            if (nm.endsWith(file)) {
                found = true;
                break;
            }
        }
    } finally {
        zipFile.close();
    }
    dst.delete();
    if (!found)
        throw new FileNotFoundException("file: " + file + " not found in " + path);
    log.info("Verification of " + path + " passed");
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

/**
 * Decompresses the file in it's current location
 *///w  w  w  .jav  a 2 s. c  o m
public void unzip() throws JahiaException {

    try {

        File f = new File(m_FilePath);

        //JahiaConsole.println(CLASS_NAME + ".upzip"," Start Decompressing " + f.getName() );

        String parentPath = f.getParent() + File.separator;
        String path = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        try {

            while ((ze = zis.getNextEntry()) != null) {
                zeName = ze.getName();
                path = parentPath + genPathFile(zeName);
                File fo = new File(path);

                if (ze.isDirectory()) {
                    fo.mkdirs();
                } else {
                    copyStream(zis, new FileOutputStream(fo));
                }
                zis.closeEntry();
            }
        } finally {

            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

        //JahiaConsole.println(CLASS_NAME+".unzip"," Decompressing " + f.getName() + " done ! ");

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException("JahiaArchiveFileHandler", "faile processing unzip",
                JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, ioe);

    }

}

From source file:org.xwoot.xwootUtil.FileUtil.java

/**
 * Extracts a zip file file to a directory.
 * <p>//from  w ww .  j a va 2s  .  co m
 * Note: The zipFile object will be closed when this method returns.
 * 
 * @param zipFile a valid ZipFile object.
 * @param destinationDirPath the directory where to extract the zip file. If it does not exist, it will be created.
 * @return a list of extracted file names.
 * @throws IOException if the destinationDirPath is not usable or other I/O or zip problems occur.
 * @see ZipFile
 * @see ZipFile#close()
 * @see #checkDirectoryPath(String)
 */
public static List<String> unzipInDirectory(ZipFile zipFile, String destinationDirPath) throws IOException {
    FileUtil.checkDirectoryPath(destinationDirPath);

    List<String> result = new ArrayList<String>();

    InputStream currentZipEntryInputStream = null;
    BufferedOutputStream bosToFile = null;

    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String currentDestinationFilePath = destinationDirPath + File.separator + entry.getName();

            currentZipEntryInputStream = zipFile.getInputStream(entry);
            bosToFile = new BufferedOutputStream(new FileOutputStream(currentDestinationFilePath));

            try {
                FileUtil.copyInputStream(currentZipEntryInputStream, bosToFile);
            } catch (IOException ioe) {
                throw new IOException(
                        "Error unzipping entry " + entry.getName() + ". Check disk space or write access.");
            }

            currentZipEntryInputStream.close();
            bosToFile.close();

            result.add(entry.getName());
        }
    } finally {
        try {
            if (currentZipEntryInputStream != null) {
                currentZipEntryInputStream.close();
            }

            if (bosToFile != null) {
                bosToFile.close();
            }

            if (zipFile != null) {
                zipFile.close();
            }
        } catch (Exception e) {
            throw new IOException("Unable to close zip file " + e.getMessage());
        }
    }

    return result;
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipListing.java

@Override
public ListingResult call() {
    final File src = getArchiveFile(resource.getLocationUri());
    if (!src.canRead() || src.isDirectory()) {
        return null;
    }//from w w  w  .j a  v  a  2 s  .  c om

    final boolean isJar = isJar(resource.getLocationUri());

    final TreeSet<String> filenames = new TreeSet<String>();

    ZipFile zf = null;
    try {
        if (isJar) {
            zf = new JarFile(src);
        } else {
            zf = new ZipFile(src);
        }

        final String path = resource.getPath();
        final int pathLen = path.length();
        for (final ZipEntry entry : Collections.list(zf.entries())) {
            String name = entry.getName();
            if (name.startsWith(path)) {
                name = name.substring(pathLen);

                if (name.startsWith("/") && name.length() > 1) {
                    name = name.substring(1);

                    if (name.indexOf("/") < 0) {
                        filenames.add(name);
                    }
                }
            }
        }

    } catch (final IOException e) {
        error = new TransferException("Failed to get listing for: %s to: %s. Reason: %s", e, resource,
                e.getMessage());
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (final IOException e) {
            }
        }
    }

    if (!filenames.isEmpty()) {
        OutputStream stream = null;
        try {
            stream = target.openOutputStream(TransferOperation.DOWNLOAD);
            stream.write(join(filenames, "\n").getBytes("UTF-8"));

            return new ListingResult(resource, filenames.toArray(new String[filenames.size()]));
        } catch (final IOException e) {
            error = new TransferException("Failed to write listing to: %s. Reason: %s", e, target,
                    e.getMessage());
        } finally {
            closeQuietly(stream);
        }
    }

    return null;
}

From source file:com.gelakinetic.mtgfam.helpers.ZipUtils.java

/**
 * Unzip a file directly into getFilesDir()
 *
 * @param zipFile The zip file to unzip//from  w ww.  j a va 2  s.c o m
 * @param context The application context, for getting files and the like
 * @throws IOException Thrown if something goes wrong with unzipping and writing
 */
private static void unZipIt(ZipFile zipFile, Context context) throws IOException {
    Enumeration<? extends ZipEntry> entries;

    entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.isDirectory()) {
            /* Assume directories are stored parents first then children.
             * This is not robust, just for demonstration purposes. */
            if (!(new File(entry.getName())).mkdir()) {
                return;
            }
            continue;
        }
        String[] path = entry.getName().split("/");
        String pathCat = "";
        if (path.length > 1) {
            for (int i = 0; i < path.length - 1; i++) {
                pathCat += path[i] + "/";
                File tmp = new File(context.getFilesDir(), pathCat);
                if (!tmp.exists()) {
                    if (!tmp.mkdir()) {
                        return;
                    }
                }
            }
        }

        InputStream in = zipFile.getInputStream(entry);
        OutputStream out;
        if (entry.getName().contains("_preferences.xml")) {
            String sharedPrefsDir = context.getFilesDir().getPath();
            sharedPrefsDir = sharedPrefsDir.substring(0, sharedPrefsDir.lastIndexOf("/")) + "/shared_prefs/";

            out = new BufferedOutputStream(new FileOutputStream(new File(sharedPrefsDir, entry.getName())));
        } else {
            out = new BufferedOutputStream(
                    new FileOutputStream(new File(context.getFilesDir(), entry.getName())));
        }
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) >= 0) {
            out.write(buffer, 0, len);
        }

        in.close();
        out.close();
    }

    zipFile.close();
}

From source file:org.omegat.filters3.xml.opendoc.OpenDocFilter.java

/**
 * Processes a single OpenDocument file, which is actually a ZIP file consisting of many XML files, some
 * of which should be translated./*from   w  ww.  j  a  v  a 2  s .com*/
 */
@Override
public void processFile(File inFile, File outFile, FilterContext fc) throws IOException, TranslationException {
    ZipFile zipfile = new ZipFile(inFile);
    ZipOutputStream zipout = null;
    if (outFile != null)
        zipout = new ZipOutputStream(new FileOutputStream(outFile));
    Enumeration<? extends ZipEntry> zipcontents = zipfile.entries();
    while (zipcontents.hasMoreElements()) {
        ZipEntry zipentry = zipcontents.nextElement();
        String shortname = zipentry.getName();
        if (shortname.lastIndexOf('/') >= 0)
            shortname = shortname.substring(shortname.lastIndexOf('/') + 1);
        if (TRANSLATABLE.contains(shortname)) {
            File tmpin = tmp();
            FileUtils.copyInputStreamToFile(zipfile.getInputStream(zipentry), tmpin);
            File tmpout = null;
            if (zipout != null)
                tmpout = tmp();

            try {
                createXMLFilter(processOptions).processFile(tmpin, tmpout, fc);
            } catch (Exception e) {
                zipfile.close();
                throw new TranslationException(
                        e.getLocalizedMessage() + "\n" + OStrings.getString("OpenDoc_ERROR_IN_FILE") + inFile);
            }

            if (zipout != null) {
                ZipEntry outentry = new ZipEntry(zipentry.getName());
                outentry.setMethod(ZipEntry.DEFLATED);
                zipout.putNextEntry(outentry);
                FileUtils.copyFile(tmpout, zipout);
                zipout.closeEntry();
            }
            if (!tmpin.delete())
                tmpin.deleteOnExit();
            if (tmpout != null) {
                if (!tmpout.delete())
                    tmpout.deleteOnExit();
            }
        } else {
            if (zipout != null) {
                ZipEntry outentry = new ZipEntry(zipentry.getName());
                zipout.putNextEntry(outentry);
                IOUtils.copy(zipfile.getInputStream(zipentry), zipout);
                zipout.closeEntry();
            }
        }
    }
    if (zipout != null)
        zipout.close();
    zipfile.close();
}

From source file:org.obiba.opal.web.FilesResourceTest.java

@SuppressWarnings("unchecked")
private void checkCompressedFolder(String folderPath, String... expectedFolderContentArray) throws IOException {
    Response response = filesResource.getFile(folderPath, null);
    ZipFile zipfile = new ZipFile(((File) response.getEntity()).getPath());

    // Check that all folders and files exist in the compressed archive that represents the folder.
    for (String anExpectedFolderContentArray : expectedFolderContentArray) {
        assertThat(zipfile.getEntry(anExpectedFolderContentArray)).isNotNull();
    }//from  w  w  w. ja  v a 2  s . co m

    Enumeration<ZipEntry> zipEnum = (Enumeration<ZipEntry>) zipfile.entries();
    int count = 0;

    while (zipEnum.hasMoreElements()) {
        zipEnum.nextElement();
        count++;
    }

    // Make sure that they are no unexpected files in the compressed archive.
    assertThat(expectedFolderContentArray.length).isEqualTo(count);

    zipfile.close();
}

From source file:com.gelakinetic.selfr.CameraActivity.java

/**
 * Helper function to return the build date of this APK
 *
 * @return A build date for this APK, or null if it could not be determined
 *//*  w  ww .  ja  v  a 2s . co m*/
private String getBuildDate() {
    try {
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
        zf.close();
        return s;
    } catch (Exception e) {
        return null;
    }
}