String to GZIP and GZIP to String, full class
class GZIPCompression {
static String compress(String string) throws IOException {
if ((string == null) || (string.length() == 0)) {
return null;
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(string.getBytes("UTF-8"));
gzip.flush();
gzip.close();
return Base64.encodeToString(obj.toByteArray(), Base64.DEFAULT);
}
static String decompress(String compressed) throws IOException {
final StringBuilder outStr = new StringBuilder();
byte[] b = Base64.decode(compressed, Base64.DEFAULT);
if ((b == null) || (b.length == 0)) {
return "";
}
if (isCompressed(b)) {
final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(b));
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
outStr.append(line);
}
} else {
return "";
}
return outStr.toString();
}
private static boolean isCompressed(final byte[] compressed) {
return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}}
for call
// test compress
String strzip="";
try {
String str = "Main TEST";
strzip=GZIPCompression.compress(str);
}catch (IOException e){
Log.e("test compress", e.getMessage());
}
//test decompress
try {
Log.e("src",strzip);
strzip = GZIPCompression.decompress(strzip);
Log.e("decompressed",strzip);
}catch (IOException e){
Log.e("test decompress", e.getMessage());
}