本文介绍了GZIPInputStream到String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我很抱歉,如果我的术语有点业余,请尽量忍受我;)

First of all, I'm sorry if my terminology is a bit amateur, try to bear with me ;)

我试图转换gzipped的身体对明文的HTTP响应。我已经采用了这个响应的字节数组并将其转换为ByteArrayInputStream。然后我将其转换为GZIPInputStream。我现在想要读取GZIPInputStream并将最终解压缩的HTTP响应体存储为明文字符串。

I am attempting to convert the gzipped body of a HTTP response to plaintext. I've taken the byte array of this response and converted it to a ByteArrayInputStream. I've then converted this to a GZIPInputStream. I now want to read the GZIPInputStream and store the final decompressed HTTP response body as a plaintext String.

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

This code will store the final decompressed contents in an OutputStream, but I want to store the contents as a String:

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的字节,您可以使用。然后,将允许您逐行阅读你的流。

To decode bytes from an InputStream, you can use an InputStreamReader. Then, a BufferedReader will allow you to read your stream line by line.

你的代码如下:

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);
}

这篇关于GZIPInputStream到String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:38