How to check if InputStream is Gzipped?

后端 未结 10 1985
一个人的身影
一个人的身影 2020-12-04 19:06

Is there any way to check if InputStream has been gzipped? Here\'s the code:

public static InputStream decompressStream(InputStream input) {
    try {
               


        
10条回答
  •  旧时难觅i
    2020-12-04 19:41

    Building on the answer by @biziclop - this version uses the GZIP_MAGIC header and additionally is safe for empty or single byte data streams.

    public static InputStream maybeDecompress(InputStream input) {
        final PushbackInputStream pb = new PushbackInputStream(input, 2);
    
        int header = pb.read();
        if(header == -1) {
            return pb;
        }
    
        int b = pb.read();
        if(b == -1) {
            pb.unread(header);
            return pb;
        }
    
        pb.unread(new byte[]{(byte)header, (byte)b});
    
        header = (b << 8) | header;
    
        if(header == GZIPInputStream.GZIP_MAGIC) {
            return new GZIPInputStream(pb);
        } else {
            return pb;
        }
    }
    

提交回复
热议问题