Thursday, 26 September 2013

Simple Example for extracting zip file in android

You can extract zip file by using
ZipInputStream
class in android.

MainActivity.java
package com.android.zipextracter;

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

import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  String zipFilePath = Environment.getExternalStorageDirectory()
    .getAbsolutePath()+"/";
  unpackZip(zipFilePath, "MyRar.zip");
 }

 private boolean unpackZip(String path, String zipname) {
  InputStream is;
  ZipInputStream zis;
  try {
   String filename;
   is = new FileInputStream(path + zipname);
   zis = new ZipInputStream(new BufferedInputStream(is));
   ZipEntry mZipEntry;
   byte[] buffer = new byte[1024];
   int count;

   while ((mZipEntry = zis.getNextEntry()) != null) {
    // zapis do souboru
    filename = mZipEntry.getName();

    // Need to create directories if not exists, or
    // it will generate an Exception...
    if (mZipEntry.isDirectory()) {
     File fmd = new File(path + filename);
     fmd.mkdirs();
     continue;
    }

    FileOutputStream fout = new FileOutputStream(path + filename);

    // cteni zipu a zapis
    while ((count = zis.read(buffer)) != -1) {
     fout.write(buffer, 0, count);
    }

    fout.close();
    zis.closeEntry();
    Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
   }

   zis.close();
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }

  return true;
 }
}


Don't forget to add following uses-permission in your manifest file


I hope this post is useful to you. kindly share your feedback as comment here.


Thank You