字符串通过gzip压缩到base64编码工具类说明

package test;

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

public class GZIPUtil {

/**
 * 压缩指定的字符串
 * @param str
 * @return
 * @throws IOException
 */
public static String compressEncode(String str) throws IOException{
    if (str == null || str.length() == 0) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
     /**
 * zip 压缩后
 * @param data
 * @return
 * @throws IOException
 */
public static String toGzip(String data) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(bos);
    GZIPOutputStream gout = new GZIPOutputStream(b64os);
    gout.write(data.getBytes("UTF-8"));
    gout.close();
    b64os.close();
    byte b1[] = bos.toByteArray();
    return  new String(b1);
}
/**
 * 对字节类型进行解压缩
 * @param bytes
 * @return
 * @throws IOException 
 */
public static String uncompressDecode(String str) throws IOException {  
    if (str == null || str.length() == 0) {
        return null;
    }
    byte[] bytes=new sun.misc.BASE64Decoder().decodeBuffer(str);
    ByteArrayOutputStream out = new ByteArrayOutputStream();  
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    if(!isGZIP(in)){
        return str;
    }
    GZIPInputStream ungzip = new GZIPInputStream(in);
    byte[] buffer = new byte[256];  
    int n;  
    while ((n = ungzip.read(buffer)) >= 0) {  
        out.write(buffer, 0, n);  
    }
    ungzip.close();
    return out.toString();
}
 
/**
 * 判断是否为gzip文件
 * @param in
 * @return
 * @throws IOException
 */
private static boolean isGZIP(InputStream in) throws IOException{
    boolean mFlag=true;
    // 取前两个字节
    byte[] header = new byte[2];
    in.read(header);
    in.reset();
    int b3=((header[1] & 0xff)<<8) |(header[0] & 0xff);
    if(b3 != GZIPInputStream.GZIP_MAGIC){
        mFlag=false;
    };
    return mFlag;
}
 
public static void main(String[] args) throws IOException {
    String str="测试字符串通过gzip压缩到base64编码";
    System.out.println("compressEncode压缩后字段"+compressEncode(str));
    System.out.println("toGzip压缩后字段"+toGzip(str));
    System.out.println("b.解压缩后字段"+uncompressDecode(compressEncode(str)));  
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值