String Compression Using GZIPOutputStream

I want to pin my string values. These string values ​​should be the same as the .net string strings.

I wrote a Decompress method, and when I send it the line znet.net, it works correctly. But the Compress method does not work correctly.

public static String Decompress(String zipText) throws IOException { int size = 0; byte[] gzipBuff = Base64.decode(zipText); ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff, 4, gzipBuff.length - 4); GZIPInputStream gzin = new GZIPInputStream(memstream); final int buffSize = 8192; byte[] tempBuffer = new byte[buffSize]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((size = gzin.read(tempBuffer, 0, buffSize)) != -1) { baos.write(tempBuffer, 0, size); } byte[] buffer = baos.toByteArray(); baos.close(); return new String(buffer, "UTF-8"); } 

-

 public static String Compress(String text) throws IOException { byte[] gzipBuff = EncodingUtils.getBytes(text, "UTF-8"); ByteArrayOutputStream bs = new ByteArrayOutputStream(); GZIPOutputStream gzin = new GZIPOutputStream(bs); gzin.write(gzipBuff); gzin.finish(); bs.close(); byte[] buffer = bs.toByteArray(); gzin.close(); return Base64.encode(buffer); } 

For example, when I send "BQAAAB + LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee ++ 997o7nU4n99 // P1xmZAFs9s5K2smeIYCqyB8 / fnwfPyLmeVlW / w + GphA2BQAAAA ==" unpack method returns the string "Hello", but when I send a "Hello" to the compression method. It returns "H4sIAAAAAAAAAMtIzcnJBwCGphA2BQAAAA ==" .

What is the problem with the compression method?

+4
android string gzip compression gzipoutputstream
source share
2 answers

Check Use Zip Stream and Base64 Encoder to Compress Big String Data

on how to use GZIPOutputStream / GZIInputStream and Base64 Encoder and Decoder to compress and decompress large string data, so it can be passed as text in the http response.

 public static String compressString(String srcTxt) throws IOException { ByteArrayOutputStream rstBao = new ByteArrayOutputStream(); GZIPOutputStream zos = new GZIPOutputStream(rstBao); zos.write(srcTxt.getBytes()); IOUtils.closeQuietly(zos); byte[] bytes = rstBao.toByteArray(); return Base64.encodeBase64String(bytes); } 

Or we can use Use Zip Stream and Base64 Encoder to compress large row data to avoid loading the entire row into memory.

 public static String uncompressString(String zippedBase64Str) throws IOException { String result = null; byte[] bytes = Base64.decodeBase64(zippedBase64Str); GZIPInputStream zi = null; try { zi = new GZIPInputStream(new ByteArrayInputStream(bytes)); result = IOUtils.toString(zi); } finally { IOUtils.closeQuietly(zi); } return result; } 
+3
source share

I tried with java vm, I suppose the result is the same. Use this line at the end of your compression method:

 return new String(base64.encode(buffer), "UTF-8"); 
0
source share

All Articles