Thursday, October 7, 2010

[Android Snippet] GZip Compression

Minimum API Level : 1

key class : GZipOutputStream , GZipInputStream

This snippet showing how to compressing file using GZipOuputStream and decompressing using GZipInputStream.

Compress


Log.v(TAG, "Start Compress");
FileInputStream fIn = new FileInputStream(INPUT_PATH);
FileOutputStream fOut = new FileOutputStream(OUTPUT_PATH);
GZIPOutputStream gZip = new GZIPOutputStream(fOut);
byte[] buf = new byte[BUFFER_SIZE];

int readCount = fIn.read(buf);
while(readCount > 0){
gZip.write(buf, 0, readCount);
readCount = fIn.read(buf);
}
gZip.finish();
gZip.close();
fIn.close();
Log.v(TAG, "Compress Success");


Decompress


Log.v(TAG, "Start Decompress");
FileInputStream fIn = new FileInputStream(INPUT_PATH);
FileOutputStream fOut = new FileOutputStream(OUTPUT_PATH);
GZIPInputStream gZip = new GZIPInputStream(fIn);
byte[] buf = new byte[BUFFER_SIZE];

int decompressCount = gZip.read(buf, 0, BUFFER_SIZE);
while(decompressCount > 0){
fOut.write(buf, 0, decompressCount);
decompressCount = gZip.read(buf, 0, BUFFER_SIZE);
}
gZip.close();
fOut.close();
Log.v(TAG, "Decompress Success");

No comments:

Post a Comment