資源描述:
《java字符串的gzip壓縮解壓縮代碼》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、JAVA字符串的GZIP壓縮解壓縮代碼packagecom.gzip;importjava.io.ByteArrayInputStream;???importjava.io.ByteArrayOutputStream;???importjava.io.IOException;???importjava.util.zip.GZIPInputStream;???importjava.util.zip.GZIPOutputStream;???//將一個字符串按照zip方式壓縮和解壓縮???publicclassZipUtil2{??????//壓縮????publicsta
2、ticStringcompress(Stringstr)throwsIOException{??????if(str==null
3、
4、str.length()==0){???????returnstr;?????}??????ByteArrayOutputStreamout=newByteArrayOutputStream();?????GZIPOutputStreamgzip=newGZIPOutputStream(out);??????gzip.write(str.getBytes());??????gzip.close();?????returnout.toStr
5、ing("ISO-8859-1");????}??????//解壓縮????publicstaticStringuncompress(Stringstr)throwsIOException{??????if(str==null
6、
7、str.length()==0){????????returnstr;????}?????ByteArrayOutputStreamout=newByteArrayOutputStream();?????ByteArrayInputStreamin=newByteArrayInputStream(str??????????.getBytes(
8、"ISO-8859-1"));??????GZIPInputStreamgunzip=newGZIPInputStream(in);??????byte[]buffer=newbyte[256];??????intn;?????while((n=gunzip.read(buffer))>=0){??????out.write(buffer,0,n);??????}??????//toString()使用平臺默認編碼,也可以顯式的指定如toString("GBK")??????returnout.toString();????}??????//測試方
9、法????publicstaticvoidmain(String[]args)throwsIOException{?????????????????//測試字符串???????Stringstr="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221";?????????????????System.out.println("原長度:"+str.length());???????????????????System
10、.out.println("壓縮后:"+ZipUtil2.compress(str).length());?????????????????System.out.println("解壓縮:"+ZipUtil2.uncompress(ZipUtil2.compress(str)));????}????}