unzip a zip file to location - Android java.util.zip

Android examples for java.util.zip:Zip

Description

unzip a zip file to location

Demo Code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.util.Log;

public class Main {

  private static final String TAG = "APKUTIL";

  public static void unzip(String zipFile, String location) throws IOException {
    try {/*from  ww w  . ja v  a2s. co m*/
      File f = new File(location);
      if (!f.isDirectory()) {
        f.mkdirs();
      }
      ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
      try {
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
          String path = location + ze.getName();

          if (ze.isDirectory()) {
            File unzipFile = new File(path);
            if (!unzipFile.isDirectory()) {
              unzipFile.mkdirs();
            }
          } else {
            FileOutputStream fout = new FileOutputStream(path, false);
            try {
              for (int c = zin.read(); c != -1; c = zin.read()) {
                fout.write(c);
              }
              zin.closeEntry();
            } finally {
              fout.close();
            }
          }
        }
      } finally {
        zin.close();
      }
    } catch (Exception e) {
      Log.e(TAG, "Unzip exception", e);
    }
  }

}

Related Tutorials