GZIPInputStream to String

2020-02-07 19:10发布

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.

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

7条回答
男人必须洒脱
2楼-- · 2020-02-07 19:34
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
    }

}
查看更多
登录 后发表回答