Pages

Friday, August 5, 2011

Extracting Zip File in Android

The code snippet below explains how to extract zip file in android
You can call extractZip method with activity from where its called and path of file to be extracted
It will extract the files on same destination path
/**
 * This method will extract the zip file from location inside application 
 * 
 * @param activity
 * @param destinationPath - Path of zip file
 * @param _location - location where file will be extracted
 * @author Yash@iotasol.com
 */
public void extractZip(Activity activity,String destinationPath,String _location ) {
System.out.println(" ctr : ::: extract zip" + zipExtracted + " : "
+ destinationPath);
FileInputStream fin = null;
ZipInputStream zin = null;
try {
fin = new FileInputStream(destinationPath);
zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
extractDirectoryZipEntry(ze.getName(), _location);
} else {
extractZipFileEntry(_location, zin, ze);
}
}
zipExtracted = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zin != null) {
zin.close();
}
if (fin != null) {
fin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}



/**
 * This method will work on every single zip entry and store it in location
 * Buffered input stream is used to speed up the downloading process
 * @param _location
 * @param zin
 * @param ze
 * @author Yash@iotasol.com
 */
private void extractZipFileEntry(String _location, ZipInputStream zin,
ZipEntry ze) {
System.out.println(">>>>> file : " + ze.getName());
FileOutputStream fout = null;
BufferedOutputStream bout = null;
try {
fout = new FileOutputStream(_location + ze.getName());
bout = new BufferedOutputStream(fout, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = zin.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
}
} catch (Exception r) {
r.printStackTrace();
} finally {
try {
zin.closeEntry();
if (bout != null)
bout.close();
if (fout != null)
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(">>>>> file downloaded: " + ze.getName());
}


/**
 * This method will work on every single zip entry in case if its a directory, and creates new
 * 
 * @param dir
 * @param _location
 * @author Yash@iotasol.com
 */
private void extractDirectoryZipEntry(String dir, String _location) {

File f = new File(_location + dir);

if (!f.isDirectory()) {
f.mkdirs();
}
}


I hope this post will be helpful. 

Please share your comments and and you can also contact me @ info@iotasol.com or visit our site www.iotasol.com , www.iotadomains.com.

No comments:

Post a Comment