Android extract zip file

In this Android tip, I am going to show you how to extract a zip file to the external storage of an Android phone. To achieve this goal, you will use the ZipFile and ZipEntry classes in java.util.zip package. These classes work in both Java and Android. An object of ZipFile is constructed passing the path of the zip file to be extracted. The entries() method of the ZipFile list all entries (files and folders) in that zip file. Each entry of the zip file can be represented by an object of the ZipEntry. With the ZipEntry object, you use the getInputStream() method to return the InputStream object that is able to read content of the entry.
Now to have an example application on extracting zip file, you create a new Android project called ExtactZip. In the activity_main.xml file, you add one EditText, one Button, and one TextView as shown below. The EditText is to display path of a zip file and allows the user to input path of a zip file. The Button labeled "Extract" is clicked to extract the zip file. The TextView displays a status message "Extracting the file. Please wait..." or "Extract completed".


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.example.extractzip.MainActivity"
  
   >
<LinearLayout
   android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
   >
  

   <EditText
     android:id="@+id/txtpath"
     android:layout_width="130dp"
     android:layout_height="wrap_content"
     android:hint="Enter file path"
     android:layout_weight="2"
     />
   <Button
     android:id="@+id/btextract"
     android:layout_width="30dp"
     android:layout_height="wrap_content"
     android:text="Extract"
     android:layout_weight="1"
     android:onClick="extractZip"
      />
   </LinearLayout>

<TextView
     android:id="@+id/txtstatus"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:paddingLeft="10dp"
  
     />

</LinearLayout>


Here is the MainActivity class that handles file extraction and save the extracted files and folders in the external storage. The file extraction task might take time. So, it is a good idea to put this task in background process to avoid unresponsive situation while the zip file is being extracted.

package com.example.extractzip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

String filepath="";
TextView txtstatus;
TextView txtpath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtstatus=(TextView)findViewById(R.id.txtstatus);
txtpath=(TextView)findViewById(R.id.txtpath);
// Get the intent object broadcast by Android when the user
// click a zip file to open from file explorer
     Intent intent=getIntent();
     String action=intent.getAction();    
     String type =intent.getType();
     // Get zip file path from intent
     if(Intent.ACTION_VIEW.equals(action) || Intent.ACTION_PICK.equals(action) && type!=""){      
       txtpath.setText(intent.getData().getPath());
      }
}
public void extractZip(View view){
String fpath=txtpath.getText().toString();
if(fpath.length()>1){
BackTask bt=new BackTask();
bt.execute(fpath,Environment.getExternalStorageDirectory()+"/extract");
}
}
// AsynnTask to run the zip file extraction in background
private class BackTask extends AsyncTask<String,String,Void>{
protected void onPreExecute(){
txtstatus.setText("Extracting the file. Please wait...");
}
protected Void doInBackground(String...params){
ZipFile zf=null;
   try {
   zf=new ZipFile(params[0]); //create a zip file object
   if(zf.size()>0){ //read through the zip file
   Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>) zf.entries();
   while(entries.hasMoreElements()){
   ZipEntry entry=entries.nextElement();
   if(!entry.isDirectory() && !entry.getName().endsWith("/")){
   //start extracting the files
   extract(zf.getInputStream(entry),entry.getName(),params[1]);
  
   }
  
   }
  
   }   

  
} catch (IOException e) {
  
Log.e("Main",e.getMessage());
  
}finally{
  if(zf!=null)
   try {
   zf.close();
   } catch (IOException e) {
   // TODO Auto-generated catch block
   Log.e("Main",e.getMessage());
   }

}
   return null;
}
protected void onPostExecute(Void result){
txtstatus.setText("Extract completed");
}
public void extract(InputStream is, String fname, String storeDir){

FileOutputStream fos;
File fi=new File(storeDir+File.separator+fname); //output file
File fparent=new File(fi.getParent());
if(!fparent.exists())
fparent.mkdirs();//create parent directories for output files

try {
  
  fos=new FileOutputStream(fi);
  int content=0;  
  while((content=is.read())!=-1){
   fos.write(content);
  }
  is.close();
  fos.close();
} catch (Exception e) {
  
  e.printStackTrace();
}

}
}


}


Before you run the example application, you need to add a permission to the AndroidManifest.xml file to allow the application to write data to the external storage.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

To allow the application to receive the file clicked on the file explorer of s Android device, you have to add the following code to the AndroidManifest.xml file.

 <intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>

Android-extract-zip-file

Posted by: Dara | post date: 10-30-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.