Saturday, April 14, 2012

Zipping File and Folder in android

Posted by Blogger Name. Category: ,

While we are attaching any folder/file to mail or other attachment so we really need to attach folder with more than one sub folder. So we need to compress it so called zipping . It necessary in Mobile OS as in Windows. So for this android provide ZipOutPutStream and ZipEntry. ZipOutPutStream read complete folder and then ZipEntry zip all the file inside folder to a new compress folder. Zipping File is very easy.If you want dynamically select which file/folder to zipped then see this

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 Compress {
private static final int BUFFER = 2048;

private String[] _files;
private String _zipFile;

public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}

public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);

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();
}

}
}


In constructor we have two string parameter.first pass array of file inside a folder .Then file path to which zipped folder will save if it is not present then this code will create new zip folder.

0 comments:

Post a Comment

◄ Posting Baru Posting Lama ►