How to check if InputStream is Gzipped?

后端 未结 10 1984
一个人的身影
一个人的身影 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 19:38

    It's not foolproof but it's probably the easiest and doesn't rely on any external data. Like all decent formats, GZip too begins with a magic number which can be quickly checked without reading the entire stream.

    public static InputStream decompressStream(InputStream input) {
         PushbackInputStream pb = new PushbackInputStream( input, 2 ); //we need a pushbackstream to look ahead
         byte [] signature = new byte[2];
         int len = pb.read( signature ); //read the signature
         pb.unread( signature, 0, len ); //push back the signature to the stream
         if( signature[ 0 ] == (byte) 0x1f && signature[ 1 ] == (byte) 0x8b ) //check if matches standard gzip magic number
           return new GZIPInputStream( pb );
         else 
           return pb;
    }
    

    (Source for the magic number: GZip file format specification)

    Update: I've just dicovered that there is also a constant called GZIP_MAGIC in GZipInputStream which contains this value, so if you really want to, you can use the lower two bytes of it.

提交回复
热议问题