Gzip解压缩 工具类(java)

工具类:

import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Gzip压缩
 * 字符串长度太小,压缩不明显
 * @author XXX
 */
public class GzipUtil {

    /**
     * 压缩
     *
     * @param strData 原字符串
     * @return 压缩后字符串
     * @throws Exception
     */
    public static String gzip(String strData) throws Exception {
        if (strData == null || strData.length() == 0) {
            return strData;
        }

        byte[] data = strData.getBytes("UTF-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(bos);
        gzip.write(data);
        gzip.finish();
        gzip.close();
        byte[] ret = bos.toByteArray();
        bos.close();
        return Base64.encodeBase64String(ret);
    }

    /**
     * 解压缩
     *
     * @param base64Str 压缩后字符串
     * @return 源字符串
     * @throws Exception
     */

    public static String unGzip(String base64Str) throws IOException {
        if (base64Str == null || base64Str.length() == 0) {
            return base64Str;
        }
        byte[] data = Base64.decodeBase64(base64Str);

        ByteArrayInputStream in = new ByteArrayInputStream(data);
        GZIPInputStream gunzip = new GZIPInputStream(in);

        byte[] buffer = new byte[1024];
        int num;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        while ((num = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, num);
        }
        gunzip.close();
        in.close();

        byte[] ret = out.toByteArray();
        out.flush();
        out.close();

        return new String(ret, "UTF-8");
    }

    /**
     * 读取文件流
     *
     * @param fileName 文件名
     * @return 字符串
     */
    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }
}

使用压缩:在这里插入图片描述
解压缩:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值