Stack Overflow archive
1 score

Android: opening large zip file

score
1
question views
995
license
CC BY-SA 3.0

If a ZipException or IOException is being thrown when initializing ZipFile then you should test the integrity of the ZIP. You may also want to make sure you have read/write access. If you are unzipping this file on Android's internal storage (sdcard) you need to have the following permission declared in your AndroidManifest.

xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

The code looks okay to me, but here is a solution I cooked up real quick and tested on a valid ZIP file larger than 100 MB:

java
public static boolean unzip(final File zipFile, final File destinationDir) {
    ZipFile zip = null;
    try {
        zip = new ZipFile(zipFile);
        final Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
        while (zipFileEntries.hasMoreElements()) {
            final ZipEntry entry = zipFileEntries.nextElement();
            final String entryName = entry.getName();
            final File destFile = new File(destinationDir, entryName);
            final File destinationParent = destFile.getParentFile();
            if (destinationParent != null && !destinationParent.exists()) {
                destinationParent.mkdirs();
            }
            if (!entry.isDirectory()) {
                final BufferedInputStream is = new BufferedInputStream(
                        zip.getInputStream(entry));
                int currentByte;
                final byte data[] = new byte[2048];
                final FileOutputStream fos = new FileOutputStream(destFile);
                final BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((currentByte = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        }
    } catch (final Exception e) {
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return true;
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.