Search code examples
androidzipunzipdirectory

Extract folders from zip in android


My application has to download a zip and has to unzip it in the application folder. The problem is that the zip doesn't have files but folders and in each folder there are different files. I would to keep the same structure but I don't know how do it. I succeed if i do it with a zip of files but not with a zip of folders. There is somebody who knows how do it? Many thanks.


Solution

  • You will need to create the directories for each directory entry in the ZIP archive. Here is a method I wrote and use that will keep the directory structure:

    /**
     * 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;
    }