JDK基础类之GZIPInputStream/GZIPOutputStream

GZIPInputStream/GZIPOutputStream是JDK用来压缩/解压缩的工具。下面是一个压缩字符串的例子:

压缩之后的大小为原来的64%左右。


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MainTest {

    public static void main(String[] args) {

        StringBuffer sb = new StringBuffer();
        String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i < 10000; i++) {
            sb.append(word.charAt((int) (Math.random() * 26)));
        }
        String a = sb.toString();
        System.out.println(a.length());
        String b = compress(a);
        System.out.println(b.length());
        String c = unCompress(b);
        System.out.println(c.length());

    }

    /**
     * @param str
     * @return
     */
    public static String compress(String str) {
        ByteArrayOutputStream bos = null;
        GZIPOutputStream out = null;
        try {
            bos = new ByteArrayOutputStream();
            out = new GZIPOutputStream(bos);
            out.write(str.getBytes());
            //这里一定要先关闭out流才能返回,不然就会出错。
            out.close();
            return bos.toString("ISO-8859-1");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String unCompress(String source) {
        if (source == null && "".equals(source)) {
            return "";
        }
        GZIPInputStream in = null;
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        try {
            bis = new ByteArrayInputStream(source.getBytes("ISO-8859-1"));
            in = new GZIPInputStream(bis);
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[256];
            int len = 0;
            while ((len = in.read(buf)) >= 0) {
                bos.write(buf, 0, len);
            }
            return bos.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally
        {
            try {
                in.close();
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值