Showing posts with label Unzipping. Show all posts
Showing posts with label Unzipping. Show all posts

Monday, 15 February 2016

HB Blog 104: How To Zip And Unzip Files In Androd Programatically???

ZIP is an archive file format that supports lossless data compression. A .ZIP file may contain one or more files or directories that may have been compressed. .ZIP files generally use the file extensions ".zip" or ".ZIP" and the MIME media type application/zip.

In Android, we can use Java's zip utility classes to compress files from sd-card. The process is as simple as normal file writing program. Just, consider normal file writing program where you copy textual data from one file to another file having extension as .txt, similarly, we can write files into another file format with extension .zip. Here, internal compression algorithum is taken care by Java's utility classes.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//ZipManager.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.example.harshalbenake.zipcompressfiles;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import android.util.Log;

public class ZipManager {
    private static final int BUFFER = 80000;

    public void zip(String[] _files, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];

            for (int i = 0; i < _files.length; i++) {
                Log.v("Compress", "Adding: " + _files[i]);
                FileInputStream fi = new FileInputStream(_files[i]);
                origin = new BufferedInputStream(fi, BUFFER);

                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;

                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unzip(String _zipFile, String _targetLocation) {
        //create target location folder if not exist
        File f = new File(_targetLocation);
        if (!f.isDirectory()) {
            f.mkdirs();
        }

        try {
            FileInputStream fin = new FileInputStream(_zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {

                //create dir if required while unzipping
                if (ze.isDirectory()) {
                    File f1 = new File(ze.getName());
                    if (!f1.isDirectory()) {
                        f1.mkdirs();
                    }
                } else {
                    FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
                    for (int c = zin.read(); c != -1; c = zin.read()) {
                        fout.write(c);
                    }

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

            }
            zin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

//MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.example.harshalbenake.zipcompressfiles;

import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MainActivity extends Activity {

    String inputPathExternal = Environment.getExternalStorageDirectory().getPath()+ "/ZipDemo/";
    String inputPathInternal = Environment.getExternalStorageDirectory()+ "/hb/";
    String inputFile = "Apply.zip";
    String outputPath = Environment.getExternalStorageDirectory().getPath()+ "/UnZipDemo/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // declare an array for storing the files
        // i.e the path of your source files
        String[] s = new String[2];

    // Type the path of the files in here
        s[0] = inputPathInternal + "/hb1.txt";
        s[1] = inputPathInternal + "/hb2.txt"; // /sdcard/ZipDemo/textfile.txt

    // first parameter is d files second parameter is zip file name
        ZipManager zipManager = new ZipManager();

    // calling the zip function
        zipManager.zip(s, inputPathInternal + inputFile);
    }

}

For unzipping files from a .zip file refer in Android you can follow my blog How To Download And Unzip File From Server In Android?

Tuesday, 23 December 2014

HB Blog 45: How To Download And Unzip File From Server In Android???

In this post, I will show how to download zip file from server into android device and then extract files from the downloaded zip file.

Android class "java.net.URLConnection" is used for downloading purpose and "java.util.zip" package is used for unzipping purpose.


I have added two separate buttons for two asynctasks for downloading and unzipping purpose separately. I first used URLConnection class to download zip file from url and used InputStream to write file into sdcard. Then, used ZipInputStream class for unzipping the same file from sdcard.

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Have a look on few code snippets,

Async_download.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
  * This class is used to download zip file.
  * @author <b>Harshal Benake</b>
  *
  */
 public class Async_download extends AsyncTask<String, String, String> {
  Activity mActivity;
  private ProgressDialog mProgressDialog;
  public Async_download(Activity activity) {
   this.mActivity=activity;
  }
  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   mProgressDialog = new ProgressDialog(mActivity);
   mProgressDialog.setMessage("Downloading 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 connection = url.openConnection();
  connection.connect();

  int lenghtOfFile = connection.getContentLength();
  
  InputStream input = new BufferedInputStream(url.openStream());
  OutputStream output = new FileOutputStream(Constant.SDCARD+Constant.FILENAME);

  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.flush();
   output.close();
   input.close();
  } catch (Exception e) {}
  return null;

  }
  protected void onProgressUpdate(String... progress) {
    mProgressDialog.setProgress(Integer.parseInt(progress[0]));
  }

  @Override
  protected void onPostExecute(String unused) {
   mProgressDialog.dismiss();
  }

Async_unzipping.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * This class is used to unzip zip file from sdcard.
 * @author <b>Harshal Benake</b>
 *
 */
public class Async_unzipping extends AsyncTask<String, String, String> {
 Activity mActivity;
 private ProgressDialog mProgressDialog;

 public Async_unzipping(Activity activity) {
  this.mActivity=activity;
 }
 
 @Override
 protected void onPreExecute() {
  super.onPreExecute();
  mProgressDialog = new ProgressDialog(mActivity);
  mProgressDialog.setMessage("Extracting file..");
  mProgressDialog.setCancelable(false);
  mProgressDialog.show();
 }
   
 @Override
 protected String doInBackground(String... params) {
   
     try  { 
       FileInputStream fin = new FileInputStream(Constant.SDCARD+Constant.FILENAME); 
       ZipInputStream zin = new ZipInputStream(fin); 
       ZipEntry ze = null; 
       while ((ze = zin.getNextEntry()) != null) {    
        
           FileOutputStream fout = new FileOutputStream(Constant.SDCARD + ze.getName()); 
           for (int c = zin.read(); c != -1; c = zin.read()) { 
             fout.write(c); 
           } 
  
           zin.closeEntry(); 
           fout.close(); 
         } 
          
       zin.close(); 
     } catch(Exception e) { 
     } 
  
   
  return null;
 } 
 
 @Override
 protected void onPostExecute(String unused) {
  mProgressDialog.dismiss();
 }