gzip - compression and decompression of string data in java -
i using following code compress , decompress string data, problem facing is, getting compressed without error, decompress method throws following error.
exception in thread "main" java.io.ioexception: not in gzip format
public static void main(string[] args) throws exception { string string = "i hhhhhhhhhhhhhhhhhhhhhhhhhhhhh" + "bjggujhhhhhhhhh" + "rggggggggggggggggggggggggg" + "esfffffffffffffffffffffffffffffff" + "esffffffffffffffffffffffffffffffff" + "esfekfgy enter code here`etd`enter code here wdd" + "heljwidgutwdbwdq8d" + "skdfgysrdsdnjsvfyekbdsgcu" +"jbujsbjvugsduddbdj"; system.out.println("after compress:"); string compressed = compress(string); system.out.println(compressed); system.out.println("after decompress:"); string decomp = decompress(compressed); system.out.println(decomp); } public static string compress(string str) throws exception { if (str == null || str.length() == 0) { return str; } system.out.println("string length : " + str.length()); bytearrayoutputstream obj=new bytearrayoutputstream(); gzipoutputstream gzip = new gzipoutputstream(obj); gzip.write(str.getbytes("utf-8")); gzip.close(); string outstr = obj.tostring("utf-8"); system.out.println("output string length : " + outstr.length()); return outstr; } public static string decompress(string str) throws exception { if (str == null || str.length() == 0) { return str; } system.out.println("input string length : " + str.length()); gzipinputstream gis = new gzipinputstream(new bytearrayinputstream(str.getbytes("utf-8"))); bufferedreader bf = new bufferedreader(new inputstreamreader(gis, "utf-8")); string outstr = ""; string line; while ((line=bf.readline())!=null) { outstr += line; } system.out.println("output string lenght : " + outstr.length()); return outstr; }
still couldn't figure out how fix issue!!!
this because of
string outstr = obj.tostring("utf-8");
send byte[]
can bytearrayoutputstream
, use such in bytearrayinputstream
construct gzipinputstream
. following changes need done in code.
byte[] compressed = compress(string); //in main method public static byte[] compress(string str) throws exception { ... ... return obj.tobytearray(); } public static string decompress(byte[] bytes) throws exception { ... gzipinputstream gis = new gzipinputstream(new bytearrayinputstream(bytes)); ... }
Comments
Post a Comment