java Gzip压缩与解压

 1 package waf.util.zip;
 2 
 3 import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.IOException;
 6 import java.util.zip.GZIPInputStream;
 7 import java.util.zip.GZIPOutputStream;
 8 
 9 public class GZip {
10 
11     public static void main(String[] args) {
12 
13     }
14 
15     public static String uncompress(byte[] src, String charset) 
16     {
17         String ret="";
18         ByteArrayInputStream bais=new ByteArrayInputStream(src);
19         ret=uncompress(bais,charset);
20         return ret;
21     }
22     public static String uncompress(ByteArrayInputStream in, String charset) {
23         try 
24         {
25             GZIPInputStream gInputStream = new GZIPInputStream(in);
26             byte[] by = new byte[1024];
27             StringBuffer strBuffer = new StringBuffer();
28             int len = 0;
29             while ((len = gInputStream.read(by)) != -1) {
30                 strBuffer.append(new String(by, 0, len, charset));
31             }
32             return strBuffer.toString();
33         }catch (IOException e) 
34         {
35             e.printStackTrace();
36         }
37         return null;
38     }
39 
40     public static byte[] compress(String str, String charset) {
41         ByteArrayOutputStream out = new ByteArrayOutputStream();
42         try {
43             GZIPOutputStream gOutputStream = new GZIPOutputStream(out);
44             gOutputStream.write(str.getBytes(charset));
45             gOutputStream.finish();
46             gOutputStream.close();
47             out.flush();
48             out.close();
49         } catch (IOException e) {
50             e.printStackTrace();
51         }
52         return out.toByteArray();
53 
54     }
55 }

 

posted @ 2020-07-26 23:22  从程序员到CTO  阅读(186)  评论(0)    收藏  举报
交流加我QQ:39667545