我无法解压缩大文件(50 mb)。
我尝试了ZipInputStream
和ZipFile
。
当我使用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);
}
}
答案 0 :(得分:1)
如果在初始化ZipException
时抛出IOException
或ZipFile
,那么您应该测试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;
}