java gzip base64,如何将字符串转换为GZIP Base64字符串?

该博客提供了一个Java示例,演示如何将字符串压缩成GZIP格式,然后转换为Base64编码。示例中使用了`GZIPOutputStream`和`Base64OutputStream`进行压缩和编码操作。在Linux环境下,可以使用`base64 -d`和`gunzip`命令验证输出结果。
摘要由CSDN通过智能技术生成

I've been trying to figure out using GZIPOutputStream's and the like but have had no success with understanding them. All I want to do is convert a string of characters - "A string of characters" into a GZIP Base64 format. How can I do this?

EDIT:

By GZIP Base64 format, I mean the string is first compressed using GZIP, then converted into Base64

解决方案

Here's a sample class:

import java.util.zip.GZIPOutputStream;

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

public class Test {

public static void main(String[] args) {

String text = "a string of characters";

try {

Base64OutputStream b64os = new Base64OutputStream(System.out);

GZIPOutputStream gzip = new GZIPOutputStream(b64os);

gzip.write(text.getBytes("UTF-8"));

gzip.close();

b64os.close();

} catch (Throwable t) {

t.printStackTrace();

}

}

}

Which outputs:

H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA

Under Linux, you can confirm this works with:

echo 'H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA' | base64 -d | gunzip

(Please note that on OSX, you should use base64 -D instead of base64 -d in the above command)

Which outputs:

a string of characters

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值