How to check if InputStream is Gzipped?

后端 未结 10 1980
一个人的身影
一个人的身影 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:48

    I found this useful example that provides a clean implementation of isCompressed():

    /*
     * Determines if a byte array is compressed. The java.util.zip GZip
     * implementation does not expose the GZip header so it is difficult to determine
     * if a string is compressed.
     * 
     * @param bytes an array of bytes
     * @return true if the array is compressed or false otherwise
     * @throws java.io.IOException if the byte array couldn't be read
     */
     public boolean isCompressed(byte[] bytes)
     {
          if ((bytes == null) || (bytes.length < 2))
          {
               return false;
          }
          else
          {
                return ((bytes[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8)));
          }
     }
    

    I tested it with success:

    @Test
    public void testIsCompressed() {
        assertFalse(util.isCompressed(originalBytes));
        assertTrue(util.isCompressed(compressed));
    }
    

提交回复
热议问题