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:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java

/**
 * INTERNAL method that returns the build date of the current APK as a string, or null if unable to determine it.
 *
 * @param context    A valid context. Must not be null.
 * @param dateFormat DateFormat to use to convert from Date to String
 * @return The formatted date, or "Unknown" if unable to determine it.
 *///from w  ww  . j  a v  a2s  .c om
private static String getBuildDateAsString(Context context, DateFormat dateFormat) {
    String buildDate;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        buildDate = dateFormat.format(new Date(time));
        zf.close();
    } catch (Exception e) {
        buildDate = "Unknown";
    }
    return buildDate;
}

From source file:org.apache.kudu.mapreduce.KuduTableMapReduceUtil.java

/**
 * Add entries to <code>packagedClasses</code> corresponding to class files
 * contained in <code>jar</code>.
 * @param jar The jar who's content to list.
 * @param packagedClasses map[class -> jar]
 *///  w  ww  .  j a  v  a2  s.  c o  m
private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
    if (null == jar || jar.isEmpty()) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
            ZipEntry entry = iter.nextElement();
            if (entry.getName().endsWith("class")) {
                packagedClasses.put(entry.getName(), jar);
            }
        }
    } finally {
        if (null != zip) {
            zip.close();
        }
    }
}

From source file:com.android.tradefed.util.FileUtil.java

/**
 * Close an open {@link ZipFile}, ignoring any exceptions.
 *
 * @param otaZip/* w w  w .  j a v  a  2s .  c  om*/
 *            the file to close
 */
public static void closeZip(ZipFile otaZip) {
    if (otaZip != null) {
        try {
            otaZip.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:ren.hankai.cordwood.mobile.MobileAppScanner.java

/**
 * ?? iOS .ipa ?//www .  java2 s  . c om
 *
 * @param filePath ipa 
 * @return ?
 * @author hankai
 * @since May 20, 2016 3:46:18 PM
 */
public static MobileAppInfo scanIosIpa(String filePath) {
    final MobileAppInfo appInfo = new MobileAppInfo();
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(filePath, Charset.forName("UTF-8"));
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        final Map<String, ZipEntry> images = new HashMap<>();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            parseIosInfoPlist(appInfo, entry, zipFile);
            if (entry.getName().toLowerCase().matches("payload/.*\\.app/.*\\.png")) {
                images.put(entry.getName(), entry);
            }
        }
        parseIosAppIcon(appInfo, zipFile, images);
    } catch (final Exception ex) {
        logger.error(String.format("Failed to parse ipa file at %s", filePath));
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (final Exception ex) {
            logger.trace("Failed to close stream.", ex);
        }
    }
    return appInfo;
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//  w ww .  j ava 2  s.  c o m

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

                String mime = new Tika().detect(newFile);
                if (mime.equals("application/x-sh") || mime.startsWith("text/"))
                    FileUtils.writeLines(newFile, FileUtils.readLines(newFile));

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static List<String> getAllClasses(ClassLoader cl, String packageName) {
    packageName = packageName.replace('.', '/');

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

    URL[] urls = ((URLClassLoader) cl).getURLs();
    for (URL url : urls) {
        //System.out.println(url.getFile());
        File jar = new File(url.getFile());

        if (jar.isDirectory()) {
            File subdir = new File(jar, packageName);
            if (!subdir.exists())
                continue;
            File[] files = subdir.listFiles();
            for (File file : files) {
                if (!file.isFile())
                    continue;
                if (file.getName().endsWith(".class"))
                    classes.add(file.getName().substring(0, file.getName().length() - 6).replace('/', '.'));
            }/*from w w w  . ja v  a2s.c  o  m*/
        }

        else {
            // try to open as ZIP
            try {
                ZipFile zip = new ZipFile(jar);
                for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
                    ZipEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (!name.startsWith(packageName))
                        continue;
                    if (name.endsWith(".class") && name.indexOf('$') < 0)
                        classes.add(name.substring(0, name.length() - 6).replace('/', '.'));
                }
                zip.close();
            } catch (ZipException e) {
                //System.out.println("Not a ZIP: " + e.getMessage());
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }
    }

    return classes;
}

From source file:org.webical.plugin.file.ZipFileExtractor.java

/**
 * Unpacks a zip file to the given destination directory
 * @param inputFile the zipfile to extract
 * @param destinationDir the destination directory
 * @throws IOException//from   w  ww .  java2  s  .com
 */
public static void unpackZipFile(File inputFile, File destinationDir) throws IOException {
    Enumeration entries;
    ZipFile zipFile;

    try {
        zipFile = new ZipFile(inputFile);

        entries = zipFile.entries();

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

            if (entry.isDirectory()) {
                if (log.isDebugEnabled()) {
                    log.debug("Extracting directory: " + destinationDir + File.separator + entry.getName());
                }
                (new File(destinationDir.getAbsolutePath() + File.separator + entry.getName())).mkdir();
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Extracting file: " + destinationDir + File.separator + entry.getName());
            }
            FileUtils.copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(destinationDir + File.separator + entry.getName())), true);
        }

        zipFile.close();
    } catch (IOException ioe) {
        log.error("Error while extracting file: " + inputFile.getAbsolutePath(), ioe);
        throw ioe;
    }
}

From source file:com.dv.util.DataViewerZipUtil.java

public static void doUnzipFile(ZipFile zipFile, File dest) throws IOException {
    if (!dest.exists()) {
        FileUtils.forceMkdir(dest);/*from   w  ww.  j  a  v  a 2s .c o m*/
    }
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(dest, entry.getName());
        if (entry.getName().endsWith(File.separator)) {
            FileUtils.forceMkdir(file);
        } else {
            OutputStream out = FileUtils.openOutputStream(file);
            InputStream in = zipFile.getInputStream(entry);
            try {
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }
    zipFile.close();
}

From source file:Zip.java

/**
 * Reads a Zip file, iterating through each entry and dumping the contents
 * to the console.//from   w  w  w  .ja  v  a2  s .  com
 */
public static void readZipFile(String fileName) {
    ZipFile zipFile = null;
    try {
        // ZipFile offers an Enumeration of all the files in the Zip file
        zipFile = new ZipFile(fileName);
        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            System.out.println(zipEntry.getName() + " contains:");
            // use BufferedReader to get one line at a time
            BufferedReader zipReader = new BufferedReader(
                    new InputStreamReader(zipFile.getInputStream(zipEntry)));
            while (zipReader.ready()) {
                System.out.println(zipReader.readLine());
            }
            zipReader.close();
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:Main.java

public static List<File> unzip(File zip, File toDir) throws IOException {
    ZipFile zf = null;
    List<File> files = null;
    try {//w  w  w  .j a v  a2 s  . c o  m
        zf = new ZipFile(zip);
        files = new ArrayList<File>();
        Enumeration<?> entries = zf.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                new File(toDir, entry.getName()).mkdirs();
                continue;
            }

            InputStream input = null;
            OutputStream output = null;
            try {
                File f = new File(toDir, entry.getName());
                input = zf.getInputStream(entry);
                output = new FileOutputStream(f);
                copy(input, output);
                files.add(f);
            } finally {
                closeQuietly(output);
                closeQuietly(input);
            }
        }
    } finally {
        if (zf != null) {
            zf.close();
        }
    }
    return files;
}