Archive

Posts Tagged ‘decompress’

Decompress file using Zip utility

October 12, 2012 Leave a comment

As I mentioned in previous post about compressing file using Zip utility, so there should be a way to de-compress zip files, too.

Here is the sample usage:

1. Utils.java

	/**
	 * to decompress file zip
	 *
	 * @param	zipFile		the target ZIP file to unzip
	 * @param	pathToUnzip	where unzipped file to be stored
	 *
	 */
	public static void decompress(String zipFile, String pathToUnzip) {

		try {
			ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
			ZipEntry entry = null;
			while((entry = zipIn.getNextEntry()) != null) {
				if(!entry.isDirectory()) {
					FileOutputStream fout = new FileOutputStream(pathToUnzip + "/" + entry.getName());
					for(int c = zipIn.read(); c != -1; c = zipIn.read()) {
						fout.write(c);
					}
					zipIn.closeEntry();
					fout.close();
				}
			}

			zipIn.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);

        doDecompress();
    }

    public void doDecompress() {
    	final String DIR_TARGET = "/sdcard/Download/Unzip";
    	final String FILE_ZIP = "/sdcard/Download/target.zip";

    	Utils.decompress(FILE_ZIP, DIR_TARGET);
    }
}

– Note  that if inside the Zip file containing also directories, then you need to check whether the __ZipEntry__ queried from ZIP file is a directory or not to create an equivalent directory while unzipping files; then just output files from zip package as normal.

 

Cheers,

Pete Houston

Categories: Home Tags: , ,