gpt4 book ai didi

java - GZIPInputStream 转字符串

转载 作者:IT老高 更新时间:2023-10-28 20:56:50 26 4
gpt4 key购买 nike

我正在尝试将 HTTP 响应的 gzip 压缩正文转换为纯文本。我已获取此响应的字节数组并将其转换为 ByteArrayInputStream。然后我将其转换为 GZIPInputStream。我现在想读取 GZIPInputStream 并将最终解压缩的 HTTP 响应正文存储为纯文本字符串。

此代码会将最终解压缩的内容存储在 OutputStream 中,但我想将内容存储为字符串:

public static int sChunk = 8192;
ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
byte[] buffer = new byte[sChunk];
int length;
while ((length = gzis.read(buffer, 0, sChunk)) != -1) {
out.write(buffer, 0, length);
}

最佳答案

要解码来自 InputStream 的字节,您可以使用 InputStreamReader .然后,一个 BufferedReader将允许您逐行阅读流水线。

您的代码将如下所示:

ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);

String readed;
while ((readed = in.readLine()) != null) {
System.out.println(readed);
}

关于java - GZIPInputStream 转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com