Archive

Posts Tagged ‘compress’

Compress file using Zip utitliy

October 12, 2012 Leave a comment

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));
			outZipStream.putNextEntry(entry);
			int count;
			while((count = inBufferStream.read(data, 0, BUFFER)) != -1) {
				outZipStream.write(data, 0, count);
			}

			inBufferStream.close();
			outZipStream.close();

		} 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. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        doCompress();
    }

    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.

 

Cheers,

Pete Houston

Advertisements
Categories: Tricks & Tips Tags: ,