Home > Tricks & Tips > Compress file using Zip utitliy

Compress file using Zip utitliy

The Android platform by default supports the compression method by using Zip utility, in case you want to do something with it. It’s on the package __java.util.zip__

This is one sample usage:

1. Utils.java

package pete.apps.samples.compressionzip;

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.String;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Utils {
	public static final int BUFFER = 2048;

	* to compress file
	* @param	file    the input file to compress
	* @param    zipFile	name of the compressed file
	public static void compress(String file, String zipFile) {
		try {

			BufferedInputStream inBufferStream = new BufferedInputStream(new FileInputStream(file), BUFFER);;
			FileOutputStream targetOutputStream = new FileOutputStream(zipFile);
			ZipOutputStream outZipStream = new ZipOutputStream(new BufferedOutputStream(targetOutputStream));

			byte data[] = new byte[BUFFER];

			ZipEntry entry = new ZipEntry(file.substring(file.lastIndexOf("/") + 1));
			int count;
			while((count = inBufferStream.read(data, 0, BUFFER)) != -1) {
				outZipStream.write(data, 0, count);


		} catch (Exception ex) {
			Log.d("Error", ex.getMessage());

2. MainScreen.java

package pete.apps.samples.compressionzip;

import android.app.Activity;
import android.os.Bundle;
import pete.apps.samples.compressionzip.Utils;

public class MainScreen extends Activity
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)


    public void doCompress() {
    	final String FILE_TARGET = "/sdcard/Download/target.txt";
    	final String FILE_ZIP = "/sdcard/Download/target.zip";

    	Utils.compress(FILE_TARGET, FILE_ZIP);

Here in my sample, I try to compress the file __target.txt__ which stored in SDCcard and try to compress it in put in the same directory __target.zip__

– In case of you have some files in your packages APK stored in __/res__ or __/raw__ or __/assets__, you need to take them out and use a __BufferedInputStream__ to write it to internal directory (local directory of your package), then get its location to compress.



Pete Houston

Categories: Tricks & Tips Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: