字符串通过gzip压缩到base64编码

方法如下:

有两种实现,一种利用原生Java API,另外使用Apache common---->IOUtils

//测试通过gz压缩->base64编码后字符串
String queryString = "I am still alive";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(bos);
GZIPOutputStream gout = new GZIPOutputStream(b64os);
gout.write(queryString.getBytes("UTF-8"));
gout.close();
b64os.close();

byte b1[] = bos.toByteArray();

System.out.println("Encode:" + new String(b1));

//		String s1 = null;
InputStream bais = new ByteArrayInputStream(b1);
Base64InputStream b64io = new Base64InputStream(bais);
GZIPInputStream gin = new GZIPInputStream(b64io);
//toString 方法建议制定编码,否则采用系统默认编码,出现中文编码错误的问题
System.out.println(IOUtils.toString(gin,"UTF-8"));

//		ByteArrayOutputStream baos = new  ByteArrayOutputStream();
//	
//		int numBytesRead = 0;
//        byte [] tempBytes = new byte[6000];
//        while ((numBytesRead = gin.read(tempBytes, 0, tempBytes.length)) != -1)
//        {
//            baos.write(tempBytes, 0, numBytesRead);
//        }
//
//        s1 = new String(baos.toByteArray());
//        s1= baos.toString();
//        System.out.println(s1);

 

 利用IOUtils能完成更多操作,不必要封装多层IO

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值