zip压缩解压
1 import java.io.ByteArrayInputStream; 2 import java.io.ByteArrayOutputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.zip.GZIPInputStream; 6 import java.util.zip.GZIPOutputStream; 7 8 import org.apache.commons.codec.binary.Base64; 9 import org.apache.commons.io.IOUtils; 10 11 /** 12 * 解压压缩工具 13 */ 14 public class Gzip { 15 16 public String unzip(String str) { 17 if (str == null || str.length() == 0) { 18 return str; 19 } 20 Base64 base64 = new Base64(); 21 byte[] bytes = base64.decode(str); 22 String json = this.uncompress(bytes, "UTF-8"); 23 return json; 24 } 25 26 public String zip(String str) { 27 if (str == null || str.length() == 0) { 28 return str; 29 } 30 Base64 base64 = new Base64(); 31 byte[] bytes = this.compress(str, "UTF-8"); 32 String json = base64.encodeToString(bytes); 33 return json; 34 } 35 36 private byte[] compress(String str, String encoding) { 37 GZIPOutputStream gzip = null; 38 ByteArrayOutputStream out = new ByteArrayOutputStream(); 39 IOStreamOperator operator = new IOStreamOperator(); 40 try { 41 gzip = new GZIPOutputStream(out); 42 gzip.write(str.getBytes(encoding)); 43 gzip.close(); 44 } 45 catch (IOException ex) { 46 ex.printStackTrace(); 47 } 48 finally { 49 operator.close(null, gzip); 50 } 51 return out.toByteArray(); 52 } 53 54 private String uncompress(byte[] bytes, String encoding) { 55 InputStream in = null; 56 GZIPInputStream gi = null; 57 IOStreamOperator operator = new IOStreamOperator(); 58 String ret = null; 59 try { 60 in = new ByteArrayInputStream(bytes); 61 gi = new GZIPInputStream(in); 62 ret = IOUtils.toString(gi, encoding); 63 } 64 catch (IOException e) { 65 e.printStackTrace(); 66 } 67 finally { 68 operator.close(gi, null); 69 } 70 return ret; 71 } 72 }