Package util; import Java. util. arrays; import java.util.zip. deflater; import java.util.zip. inflater; import Org. apache. commons. codec. binary. base64; public class stringzlibutil {/*** use zlib to compress * @ Param message * @ return * @ throws exception */public static byte [] zlibcompress (string message) throws exception {string chatacter = "UTF-8"; byte [] input = message. getbytes (chatacter); system. out. println ("input length" + input. length); byte [] Output = new byte [input. length + 10 + new double (math. ceil (input. length * 0.25f )). intvalue ()]; system. out. println (output. length); Deflater compresser = new Deflater (); compresser. setinput (input); compresser. finish (); int compresseddatalength = compresser. deflate (output); system. out. println ("compresseddatalength" + compresseddatalength); compresser. end (); // string ostr = new string (output, 0, compresseddatalength, chatacter); // system. out. println ("Out Str" + ostr); Return arrays. copyof (output, compresseddatalength );} /*** decompress ** @ Param Barr the byte array to be decompressed * @ Param charater encoding method for compression * @ return * @ throws exception */public static byte [] zlibinfcompress (byte [] Barr, string charater) throws exception {byte [] result = new byte [2014]; Inflater inf = new Inflater (); INF. setinput (Barr); int inflen = inf. inflate (result); INF. end (); string strogr = new string (result, charater); system. out. println ("str OGR" + strogr); Return arrays. copyof (result, inflen);} public static void main (string [] ARGs) throws exception {string STR = "ABCDE | qqqqqqqqqqqqqqq | wwwwwwwwwwwwwwwwwwwwwwww"; // Method 1: /* byte [] def = stringzlibutil. zlibcompress (STR); byte [] INF = stringzlibutil. zlibinfcompress (def, "UTF-8"); string strogr = new string (INF, "UTF-8"); system. out. println ("str org main" + strogr); * // Method 2: encode and decode the basic base64 byte [] def = stringzlibutil. zlibcompress (STR); string strbase = base64.encodebase64string (DEF); system. out. println ("str base64 string" + strbase); byte [] decstr = base64.decodebase64 (strbase); byte [] decode_str = stringzlibutil. zlibinfcompress (decstr, "UTF-8"); string decstrogr = new string (decode_str, "UTF-8"); system. out. println ("decstrogr" + decstrogr );}}
Deflater and Inflater compression and decompression