Android:打开大型zip文件

时间:2014-12-08 05:49:52

标签: android zip zipfile

我无法解压缩大文件(50 mb)。 我尝试了ZipInputStreamZipFile

当我使用ZipFile时,我收到以下异常:

  

java.util.zip.ZipException:未找到EOCD;不是Zip档案?

当我使用ZipInputStream时,我收到了关注错误:

  

没有zip条目(zin.getNextEntry())

ZipInputStream代码:

public static void unzip(File _zipFile, File directory) throws IOException {
    try {
        FileInputStream fin = new FileInputStream(_zipFile);
        ZipInputStream zin = new ZipInputStream(fin);
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            // not getting here
        }
        zin.close();
    }
    catch (Exception e) {
    }
}

ZipFile代码:

public static void unzipa(File zipfile, File directory) throws IOException {
    try {
        ZipFile zfile = new ZipFile(zipfile); // getting exception here
        Enumeration<? extends ZipEntry> entries = zfile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

        }
        zfile.close();
    }
    catch (Exception ex) {
        ErroHandling.HandleError(ex);
    }

}

1 个答案:

答案 0 :(得分:1)

如果在初始化ZipException时抛出IOExceptionZipFile,那么您应该测试ZIP的完整性。您可能还希望确保您具有读/写访问权限。如果您要在Android内部存储(SD卡)上解压缩此文件,则需要在AndroidManifest中声明以下权限。

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

代码对我来说没问题,但这是一个我真正快速编写并在大于100 MB的有效ZIP文件上测试的解决方案:

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;
}
相关问题