Java GZIPInputStream 转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3627401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GZIPInputStream to String
提问by Matt
First of all, I'm sorry if my terminology is a bit amateur, try to bear with me ;)
首先,如果我的术语有点业余,我很抱歉,请耐心等待;)
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.
我正在尝试将 HTTP 响应的压缩正文转换为纯文本。我已获取此响应的字节数组并将其转换为 ByteArrayInputStream。然后我将其转换为 GZIPInputStream。我现在想读取 GZIPInputStream 并将最终解压缩的 HTTP 响应正文存储为纯文本字符串。
This code will store the final decompressed contents in an OutputStream, but I want to store the contents as a String:
此代码将最终解压缩的内容存储在 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);
}
采纳答案by Vivien Barousse
To decode bytes from an InputStream, you can use an InputStreamReader. Then, a BufferedReaderwill allow you to read your stream line by line.
要从 InputStream 解码字节,您可以使用InputStreamReader。然后,BufferedReader将允许您逐行读取流。
Your code will look like:
您的代码将如下所示:
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);
}
回答by Gopi
You can use the StringWriterto write to String
您可以使用StringWriter写入 String
回答by BalusC
You should rather have obtained the response as an InputStream
instead of as byte[]
. Then you can ungzip it using GZIPInputStream
and read it as character data using InputStreamReader
and finally write it as character data into a String
using StringWriter
.
您应该获得作为 anInputStream
而不是 as的响应byte[]
。然后您可以使用解压缩它GZIPInputStream
并将其作为字符数据 using 读取InputStreamReader
,最后将其作为字符数据写入String
using StringWriter
。
String body = null;
String charset = "UTF-8"; // You should determine it based on response header.
try (
InputStream gzippedResponse = response.getInputStream();
InputStream ungzippedResponse = new GZIPInputStream(gzippedResponse);
Reader reader = new InputStreamReader(ungzippedResponse, charset);
Writer writer = new StringWriter();
) {
char[] buffer = new char[10240];
for (int length = 0; (length = reader.read(buffer)) > 0;) {
writer.write(buffer, 0, length);
}
body = writer.toString();
}
// ...
See also:
也可以看看:
If your final intent is to parse the response as HTML, then I strongly recommend to just use a HTML parser for this like Jsoup. It's then as easy as:
如果您的最终意图是将响应解析为 HTML,那么我强烈建议您只使用 HTML 解析器,例如Jsoup。然后就这么简单:
String html = Jsoup.connect("http://google.com").get().html();
回答by Pana Emp
import java.io.*;
import java.util.zip.*;
public class Ex1 {
public static void main(String[] args) throws Exception{
String str ;
H h1 = new H();
h1.setHcfId("PH12345658");
h1.setHcfName("PANA HEALTH ACRE FACILITY");
str = h1.toString();
System.out.println(str);
if (str == null || str.length() == 0) {
return ;
}
ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
out.close();
String s = out.toString() ;
System.out.println( s );
byte[] ba = out.toByteArray();
System.out.println( "---------------BREAK-------------" );
ByteArrayInputStream in = new ByteArrayInputStream(ba);
GZIPInputStream gzis = new GZIPInputStream(in);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader pr = new BufferedReader(reader);
String readed;
while ((readed = pr.readLine()) != null) {
System.out.println(readed);
}
//Close all the streams
}
}
回答by ChaitanyaBhatt
Use Apache Commons to convert GzipInputStream to byteArray.
使用 Apache Commons 将 GzipInputStream 转换为 byteArray。
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.IOUtils;
public static byte[] decompressContent(byte[] pByteArray) throws IOException {
GZIPInputStream gzipIn = null;
try {
gzipIn = new GZIPInputStream(new ByteArrayInputStream(pByteArray));
return IOUtils.toByteArray(gzipIn);
} finally {
if (gzipIn != null) {
gzipIn.close();
}
}
To convert byte array uncompressed content to String, do something like this :
要将字节数组未压缩的内容转换为字符串,请执行以下操作:
String uncompressedContent = new String(decompressContent(inputStream));
回答by Misam Abbas
Use the try-with-resources idiom (which automatically closes any resources opened in try(...) on exit from the block) to make code cleaner.
使用 try-with-resources 习惯用法(它会在退出块时自动关闭在 try(...) 中打开的任何资源)使代码更清晰。
Use Apache IOUtils to convert inputStream to String using default CharSet.
使用 Apache IOUtils 使用默认 CharSet 将 inputStream 转换为 String。
import org.apache.commons.io.IOUtils;
public static String gzipFileToString(File file) throws IOException {
try(GZIPInputStream gzipIn = new GZIPInputStream(new FileInputStream(file))) {
return IOUtils.toString(gzipIn);
}
}
回答by Alexander Byrd
you can also do
你也可以这样做
try (GZIPInputStream gzipIn = new GZIPInputStream(new ByteArrayInputStream(pByteArray)))
{
....
}
AutoClosable is a good thing https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
AutoClosable 是一件好事 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html