在Java中解压缩GZip字符串 [英] Decompress GZip string in Java
问题描述
我可以找到很多可以解压缩GZip文件的函数,但是如何解压缩GZip字符串?
I can find plenty of functions that let you decompress a GZip file, but how do I decompress a GZip string?
我正在尝试解析HTTP响应使用GZip压缩响应体的位置。但是,整个响应只是存储在一个字符串中,因此字符串的一部分包含二进制字符。
I'm trying to parse a HTTP response where the response body is compressed with GZip. However, the entire response is simply stored in a string so part of the string contains binary chars.
我正在尝试使用:
byte responseBodyBytes[] = responseBody.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(responseBodyBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
但这只会引发异常:java.io.IOException:不是GZIP格式
But that just throws an exception: java.io.IOException: Not in GZIP format
推荐答案
没有GZip字符串这样的东西。 GZip是二进制的,字符串是文本。
There's no such thing as a GZip string. GZip is binary, strings are text.
如果要压缩字符串,则需要先将其转换为二进制 - 例如与 OutputStreamWriter
链接到压缩 OutputStream
(例如 GZIPOutputStream
)
If you want to compress a string, you need to convert it into binary first - e.g. with OutputStreamWriter
chained to a compressing OutputStream
(e.g. a GZIPOutputStream
)
同样地读取数据,您可以使用 InputStreamReader
链接到解压缩 InputStream
(例如 GZIPInputStream
)。
Likewise to read the data, you can use an InputStreamReader
chained to a decompressing InputStream
(e.g. a GZIPInputStream
).
从轻松阅读的一种方法Reader
是使用番石榴或类似的图书馆。
One way of easily reading from a Reader
is to use CharStreams.toString(Readable)
from Guava, or a similar library.
这篇关于在Java中解压缩GZip字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!