17

I have a zipped password protected a video file saved on sd card on android emulator. Now i want to unzip that video file on sd card through code. How can i achieve that? Any help or code? Thanks in advance

Suhail Larik
  • 229
  • 1
  • 3
  • 10
  • http://www.google.com/search?q=android+unzip+file – Caner Oct 08 '11 at 14:42
  • Have a look at ZipInputStream from the Android developer site: http://developer.android.com/reference/java/util/zip/ZipFile.html – Seph Oct 09 '11 at 11:32
  • 1
    This question has been asked many times before. It's in the Java library rather than the Android one. See here: http://stackoverflow.com/questions/3382996/how-to-unzip-files-programmatically-in-android – HXCaine Oct 09 '11 at 11:32
  • 1
    Kotlin solution here - https://stackoverflow.com/a/50990872/1162784 It uses a File extension. – arsent Jun 22 '18 at 15:34
  • Possible duplicate of [How to unzip files programmatically in Android?](https://stackoverflow.com/questions/3382996/how-to-unzip-files-programmatically-in-android) – arsent Jun 22 '18 at 15:36
  • See this method: https://stackoverflow.com/a/76032406/12272687 – Mori Apr 17 '23 at 06:56

4 Answers4

23
import android.util.Log; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 

/** 
 * 
 * @author jon 
 */ 
public class Decompress { 
  private String _zipFile; 
  private String _location; 

  public Decompress(String zipFile, String location) { 
    _zipFile = zipFile; 
    _location = location; 

    _dirChecker(""); 
  } 

  public void unzip() { 
    try  { 
      FileInputStream fin = new FileInputStream(_zipFile); 
      ZipInputStream zin = new ZipInputStream(fin); 
      ZipEntry ze = null; 
      while ((ze = zin.getNextEntry()) != null) { 
        Log.v("Decompress", "Unzipping " + ze.getName()); 

        if(ze.isDirectory()) { 
          _dirChecker(ze.getName()); 
        } else { 
          FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
          for (int c = zin.read(); c != -1; c = zin.read()) { 
            fout.write(c); 
          } 

          zin.closeEntry(); 
          fout.close(); 
        } 

      } 
      zin.close(); 
    } catch(Exception e) { 
      Log.e("Decompress", "unzip", e); 
    } 

  } 

  private void _dirChecker(String dir) { 
    File f = new File(_location + dir); 

    if(!f.isDirectory()) { 
      f.mkdirs(); 
    } 
  } 
} 

In your case::

String zipFilename = Environment.getExternalStorageDirectory() + "/files.zip"; 
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipped/"; 

Decompress d = new Decompress(zipFilename, unzipLocation); 
d.unzip(); 
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • 2
    Divyesh Thanks for reply. But still i m confused because my zipped file is password protected so how i will match that password to enter in the file? – Suhail Larik Oct 08 '11 at 17:08
  • 17
    Just a complement to your answer, the actual entry read and file writing could be done in chunks for much higher performance instead of byte by byte: `byte[] buffer = new byte[4096]; for (int c = zin.read(buffer); c != -1; c = zin.read(buffer)) { fout.write(buffer, 0, c); }` – Rafael Nobre Jul 26 '12 at 13:29
  • 1
    @nobre do you think same code works for unzipping or unpacking the expansion APK Expansion Files obb files? – LOG_TAG Aug 02 '12 at 05:16
  • Here is a Xamarin.Android version: https://gist.github.com/pauldendulk/18958a610adb50990d96 – pauldendulk Apr 28 '15 at 17:18
5

To unpacking the password protected file use this library:

http://www.lingala.net/zip4j/download.php

it is so easy.

ZipFile zipFile = new ZipFile(YourZipFile);
if(zipFile.isEncrypted())
    zipFile.setPassword(Password);
zipFile.extractAll(Destination);
Behrouz.M
  • 3,445
  • 6
  • 37
  • 64
2

This is slightly more cleaner version of Samir's code with using Apache's IOUtils.copy() for copying files and finally block. If you have large files in archive then better use IOUtils.copyLarge().

import org.apache.commons.io.IOUtils;

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

public class ZipUtils {
    public static void unzip(InputStream is, File path) {
        checkDir(path);
        ZipInputStream zis = null;
        FileOutputStream fos = null;
        try {
            zis = new ZipInputStream(is);
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                File entryFile = new File(path, ze.getName());
                if (ze.isDirectory()) {
                    checkDir(entryFile);
                } else {
                    fos = new FileOutputStream(entryFile);
                    IOUtils.copy(zis, fos);
                    fos.close();
                    fos = null;
                }
                zis.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException ignore) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private static void checkDir(File path) {
        if (!path.exists()) {
            path.mkdirs();
        } else if (!path.isDirectory()) {
            throw new IllegalArgumentException("Path is not directory");
        }
    }
}
mixel
  • 25,177
  • 13
  • 126
  • 165
2

Other answers not really work on sdcard(Environment.getExternalStorageDirectory() != SDCARD) in kitkat and above. but you can use this code for api 21 and above! for more help to get zipDocumentFile read this :

/**
 * @return true->successful
 */
public static Boolean unzip(Context context, DocumentFile zipDocumentFile) {

    try {

        InputStream inputStream = context.getContentResolver().openInputStream(zipDocumentFile.getUri());
        assert inputStream != null;
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream, BUFFER_SIZE));

        ZipEntry ze;
        while ((ze = zipInputStream.getNextEntry()) != null) {
            if (ze.isDirectory()) {

                String[] paths = ze.getName().split("/");

                DocumentFile documentFile = null;
                for (String path : paths) {
                    if (documentFile == null) {
                        documentFile = zipDocumentFile.getParentFile().findFile(path);
                        if (documentFile == null)
                            documentFile = zipDocumentFile.getParentFile().createDirectory(path);
                    } else {
                        DocumentFile newDocumentFile = documentFile.findFile(path);
                        if (newDocumentFile == null) {
                            documentFile = documentFile.createDirectory(path);
                        } else {
                            documentFile = newDocumentFile;
                        }
                    }
                }

                if (documentFile == null || !documentFile.exists())
                    return false;

            } else {

                String[] paths = ze.getName().split("/");

                //Make Folders
                DocumentFile documentFile = null;
                for (int i = 0; i < paths.length - 1; i++) {
                    if (documentFile == null) {
                        documentFile = zipDocumentFile.getParentFile().findFile(paths[i]);
                        if (documentFile == null)
                            documentFile = zipDocumentFile.getParentFile().createDirectory(paths[i]);
                    } else {
                        DocumentFile newDocumentFile = documentFile.findFile(paths[i]);
                        if (newDocumentFile == null) {
                            documentFile = documentFile.createDirectory(paths[i]);
                        } else {
                            documentFile = newDocumentFile;
                        }
                    }
                }

                DocumentFile unzipDocumentFile;
                if (documentFile == null) {
                    unzipDocumentFile = zipDocumentFile.getParentFile().createFile(URLConnection.guessContentTypeFromName(ze.getName()), paths[paths.length - 1]);
                } else {
                    unzipDocumentFile = documentFile.createFile(URLConnection.guessContentTypeFromName(ze.getName()), paths[paths.length - 1]);

                }


                // unzip the file
                OutputStream outputStream = context.getContentResolver().openOutputStream(unzipDocumentFile.getUri());

                int read;
                byte[] data = new byte[BUFFER_SIZE];
                assert outputStream != null;
                while ((read = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1)
                    outputStream.write(data, 0, read);

                zipInputStream.closeEntry();

            }
        }

        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}
Javad
  • 361
  • 5
  • 9