android - 从android中的zip中提取文件夹

标签 android zip unzip directory

我的应用程序必须下载一个 zip 文件并将其解压缩到应用程序文件夹中。问题是 zip 没有文件,而是文件夹,并且每个文件夹中都有不同的文件。我想保持相同的结构,但我不知道该怎么做。如果我使用文件压缩而不是文件夹压缩,我会成功。 有人知道怎么做吗? 非常感谢。

最佳答案

您需要为 ZIP 存档中的每个目录条目创建目录。这是我编写和使用的一种方法,它将保持目录结构:

/**
 * Unzip a ZIP file, keeping the directory structure.
 *
 * @param zipFile
 *     A valid ZIP file.
 * @param destinationDir
 *     The destination directory. It will be created if it doesn't exist.
 * @return {@code true} if the ZIP file was successfully decompressed.
 */
public static boolean unzip(File zipFile, File destinationDir) {
  ZipFile zip = null;
  try {
    destinationDir.mkdirs();
    zip = new ZipFile(zipFile);
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
    while (zipFileEntries.hasMoreElements()) {
      ZipEntry entry = zipFileEntries.nextElement();
      String entryName = entry.getName();
      File destFile = new File(destinationDir, entryName);
      File destinationParent = destFile.getParentFile();
      if (destinationParent != null && !destinationParent.exists()) {
        destinationParent.mkdirs();
      }
      if (!entry.isDirectory()) {
        BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
        int currentByte;
        byte data[] = new byte[DEFUALT_BUFFER];
        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, DEFUALT_BUFFER);
        while ((currentByte = is.read(data, 0, DEFUALT_BUFFER)) != EOF) {
          dest.write(data, 0, currentByte);
        }
        dest.flush();
        dest.close();
        is.close();
      }
    }
  } catch (Exception e) {
    return false;
  } finally {
    if (zip != null) {
      try {
        zip.close();
      } catch (IOException ignored) {
      }
    }
  }
  return true;
}

关于android - 从android中的zip中提取文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40849308/

相关文章:

python - 你如何在python中解压缩非常大的文件?

java - 如何使用 Java 解压缩由 Linux 创建的受密码保护的存档

android - 如何在 Android 上使用 Hamcrest 匹配器和 jUnit

Android Studio : ButterKnife 6. 1.0 重复类:$$View Injector

java - 如何使用 Java 压缩/解压缩文件夹及其所有文件和子目录?

java - 维护 zip 文件中的 Windows 目录

java - 通过php检索sql数据库中的一行并将输出转换为android应用程序中的textView

java - 如何使用 Retrofit 为所有请求定义一个 Header?

用于就地修改 ZIP 文件的 C++ 库

linux - 解压后更改目录