Copyright (c) 2013 Lorenz Lehmann
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Sof...
If you think the Android project sodf listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package lal.sodf.framework.compressor;
/*www.java2s.com*/import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import android.util.Log;
/**
* A compression algorithm based on the Android implementation of GZIP.
* The code used in the compression and decompression method was written by StackOverflow user "scessor".
* The original example can be found here: http://stackoverflow.com/questions/6717165/how-can-i-zip-and-unzip-a-string-using-gzipoutputstream-that-is-compatible-with
* The code has been slightly modified to be used
* @author scessor, Lorenz Lehmann
*
*/publicclass Gzip implements CompressionAlgorithm{
@Override
publicbyte[] compress(String string) {
try {
if (string == null || string.length() <= 0) returnnewbyte[0];
byte[] blockcopy = ByteBuffer
.allocate(4)
.order(java.nio.ByteOrder.LITTLE_ENDIAN)
.putInt(string.length())
.array();
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes("UTF-8"));
gos.close();
os.close();
byte[] compressed = newbyte[4 + os.toByteArray().length];
System.arraycopy(blockcopy, 0, compressed, 0, 4);
System.arraycopy(os.toByteArray(), 0, compressed, 4, os.toByteArray().length);
return compressed;
} catch (IOException e){
Log.e(getClass().getSimpleName(), "Error on compression "+e);
returnnew String("ERROR").getBytes();
}
}
@Override
public String decompress(byte[] compressed) {
try {
finalint BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(compressed, 4, compressed.length - 4);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
InputStreamReader reader = new InputStreamReader(gis, "UTF-8");
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String read;
while ((read = in.readLine()) != null) {
sb.append(read);
}
in.close();
reader.close();
gis.close();
is.close();
return sb.toString();
} catch (IOException e){
Log.e(getClass().getSimpleName(), "Error on decompression "+e);
returnnew String("ERROR");
}
}
@Override
public String getIdentifier() {
return"gzip";
}
}