1

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(); 
    } 
  } 
}
Varsha B.
  • 41
  • 3
  • 7

1 Answers1

3

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

Community
  • 1
  • 1
Hasnain
  • 274
  • 2
  • 14
  • my above program unzips all the files into a given destination directory..It shows the path in Log-cat as "test\FolderManager\Company245\1cover.jpg"..How to read this files because it contains backslash? – Varsha B. Aug 26 '14 at 10:38
  • File imgFile = new File("/sdcard/" + FileName); then open Actually you are using the wrong slash symbol – Hasnain Aug 26 '14 at 10:42
  • can you explain me that how the structure of file you have file is always save with the forward slashes not with the backslash as i know. – Hasnain Aug 26 '14 at 11:19
  • When I extracts the zip, following is the files i got in folder,so i am not able to read this files.. test\10228.json , test\FolderManager\Company245\1cover.jpg , test\FolderManager\Company245\Project1\PrivateData\31images.jpg – Varsha B. Aug 26 '14 at 11:42
  • @VarshaB. if you ever go in the my files folder in android phone the you go in the all file folder then you can easily see on the top how android manage there folder android always manage there folder like this /storage/emulated/temp not like this\storage\emulated\temp – Hasnain Aug 26 '14 at 11:55
  • @VarshaB. hello have u find any solution for backward slash if yes then pls. update your answer – Ando Masahashi Dec 17 '14 at 02:12