如何将字符串转换为GZIP Base64字符串?
我一直试图找出使用 GZIPOutputStream 等等但是没有成功理解它们。我想做的就是将一串字符 - 一串字符转换为GZIP Base64格式。我该怎么做?
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?
编辑:
通过GZIP Base64格式,我的意思是首先使用GZIP压缩字符串,然后转换为Base64
By GZIP Base64 format, I mean the string is first compressed using GZIP, then converted into Base64
使用 Apache Commons Codec Base64OutputStream
。
这是一个示例类:
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();
}
}
}
哪些输出:
H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA
在Linux下,您可以确认这适用于:
Under Linux, you can confirm this works with:
echo 'H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA' | base64 -d | gunzip
(请注意,在OSX上,你应该使用 base64 -D
而不是上面命令中的 base64 -d
(Please note that on OSX, you should use base64 -D
instead of base64 -d
in the above command)
哪些输出:
a string of characters