java gzip 压缩字符串

package cn.shinkong.cxf.util;


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

import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.util.Base64;

public class Gzip_date {
	
    /** 字符串压缩为字节数组
	 * @param String 源数据
	 * @return String 压缩后的数据
	 */
    public static String compressToByte(String str){
        if (str == null || str.length() == 0) {
            return null;
        }
        //实现了一个输出流,其中的数据被写入一个 byte 数组。
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //GZIP 文件格式写入压缩数据实现流过滤器
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            //将字节数组写入压缩输出流。
            gzip.write(str.getBytes("utf-8"));
            gzip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //BASE64转码
        return Base64.encode(out.toByteArray());
    }
 
    /*
     * 字节数组解压缩后返回字符串
     */
    public static String uncompressToString(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
		try {
			in = new ByteArrayInputStream(Base64.decode((str)));
		} catch (WSSecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        try {
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            //gunzip.read(buffer) 将未压缩数据读入字节数组。
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
	 * 将字节数组转换成16进制字符串
	 * 
	 * @param buf
	 * @return
	 */
    public static String bytesToHexString(byte[] src) {  
        StringBuilder stringBuilder = new StringBuilder("");  
        if (src == null || src.length <= 0) {  
            return null;  
        }  
        for (int i = 0; i < src.length; i++) {  
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2) {  
                stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString();  
    }  

}


 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值