Varsha B.
Varsha B.

Reputation: 41

program to download zip file from url and extract with the proper directory structures in android

Hello please suggest me the program to download zip file from url and extract with the proper directory structures in android. Actually i have written code for this but This program does not maintain the folder structure. It unzips all the files into a given destination directory. Please suggest.

  public class AndroidQAActivity extends Activity {
      EditText eText;
      private static Random random = new Random(Calendar.getInstance().getTimeInMillis());
      private ProgressDialog mProgressDialog;
        String unzipLocation = Environment.getExternalStorageDirectory() + "/test.zip/";
        String zipFile =Environment.getExternalStorageDirectory() + "/test.zip";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // setContentView(R.layout.main);
    DownloadMapAsync mew = new DownloadMapAsync();
    mew.execute("http://alphapluss.ecotechservices.com/Downloads/10228.zip");

  }


class DownloadMapAsync extends AsyncTask<String, String, String> {
       String result ="";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(AndroidQAActivity.this);
        mProgressDialog.setMessage("Downloading Zip File..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();


    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try {


    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();
    int lenghtOfFile = conexion.getContentLength();
    InputStream input = new BufferedInputStream(url.openStream());

    OutputStream output = new FileOutputStream(zipFile);

    byte data[] = new byte[1024];
    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }
        output.close();
        input.close();
        result = "true";

    } catch (Exception e) {

        result = "false";
    }
    return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        mProgressDialog.dismiss();
        if(result.equalsIgnoreCase("true")){
        try {
            unzip();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
        else{

        }
    }
}



  public void unzip() throws IOException {
        mProgressDialog = new ProgressDialog(AndroidQAActivity.this);
        mProgressDialog.setMessage("Please Wait...Extracting zip file ... ");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        new UnZipTask().execute(zipFile, unzipLocation);
         }




private class UnZipTask extends AsyncTask<String, Void, Boolean> {
  @SuppressWarnings("rawtypes")
  @Override
  protected Boolean doInBackground(String... params) {
      String filePath = params[0];
      String destinationPath = params[1];

      File archive = new File(filePath);
      try {


         ZipFile zipfile = new ZipFile(archive);
          for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
              ZipEntry entry = (ZipEntry) e.nextElement();
              unzipEntry(zipfile, entry, destinationPath);
          }


            UnzipUtil d = new UnzipUtil(zipFile, unzipLocation); 
            d.unzip();

      } catch (Exception e) {

          return false;
      }

      return true;
  }

  @Override
  protected void onPostExecute(Boolean result) {
      mProgressDialog.dismiss();

  }


  private void unzipEntry(ZipFile zipfile, ZipEntry entry,
          String outputDir) throws IOException {

      if (entry.isDirectory()) {
          createDir(new File(outputDir, entry.getName())); 
          return;
      }

      File outputFile = new File(outputDir, entry.getName());
      if (!outputFile.getParentFile().exists()) {
          createDir(outputFile.getParentFile());
      }

     // Log.v("", "Extracting: " + entry);
      BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
      BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

      try {

      } finally {
        outputStream.flush();
        outputStream.close();
        inputStream.close();


      }
  }

  private void createDir(File dir) {
      if (dir.exists()) {
          return;
      }
      if (!dir.mkdirs()) {
          throw new RuntimeException("Can not create dir " + dir);
      }
  }}


}



       **And this is my UnzipUtil Class**

       public class UnzipUtil { 
  private String _zipFile; 
  private String _location; 

  public UnzipUtil(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); 


            byte[] buffer = new byte[8192];
             int len;
             while ((len = zin.read(buffer)) != -1) {
                 fout.write(buffer, 0, len);
             }
             fout.close();

        //  } 

          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(); 
    } 
  } 
}

Upvotes: 1

Views: 9490

Answers (1)

Hasnain
Hasnain

Reputation: 272

I am sharing some url with you first of all you want to down load the file like shown in the following link of stackoverflow

Download a file programatically on Android And then Extract the file from zip like shown in the following link Android Unzipping files Programmatically in android

Upvotes: 3

Related Questions