58

有什么方法可以检查 InputStream 是否已被压缩?这是代码:

public static InputStream decompressStream(InputStream input) {
    try {
        GZIPInputStream gs = new GZIPInputStream(input);
        return gs;
    } catch (IOException e) {
        logger.info("Input stream not in the GZIP format, using standard format");
        return input;
    }
}

我尝试过这种方式,但它没有按预期工作 - 从流中读取的值无效。编辑:添加了我用来压缩数据的方法:

public static byte[] compress(byte[] content) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        GZIPOutputStream gs = new GZIPOutputStream(baos);
        gs.write(content);
        gs.close();
    } catch (IOException e) {
        logger.error("Fatal error occured while compressing data");
        throw new RuntimeException(e);
    }
    double ratio = (1.0f * content.length / baos.size());
    if (ratio > 1) {
        logger.info("Compression ratio equals " + ratio);
        return baos.toByteArray();
    }
    logger.info("Compression not needed");
    return content;

}
4

10 回答 10

76

这不是万无一失的,但它可能是最简单的并且不依赖任何外部数据。像所有体面的格式一样,GZip 也以一个幻数开头,无需阅读整个流即可快速检查。

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

(幻数来源:GZip 文件格式规范

更新:我刚刚发现还有一个包含这个值的常量被调用,所以如果你GZIP_MAGIC真的想要,你可以使用它的低两个字节。GZipInputStream

于 2011-01-27T16:24:42.543 回答
40

InputStream 来自 HttpURLConnection#getInputStream()

在这种情况下,您需要检查 HTTPContent-Encoding响应标头是否等于gzip.

URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();

if ("gzip".equals(connection.getContentEncoding())) {
    input = new GZIPInputStream(input);
}

// ...

这一切都在HTTP 规范中明确规定。


更新:根据您压缩流源的方式:这个比率检查非常......疯狂。摆脱它。相同的长度并不一定意味着字节相同。让它始终返回 gzipped 流,以便您始终可以期待 gzipped 流并且GZIPInputStream无需讨厌的检查即可应用。

于 2011-01-27T15:58:00.700 回答
27

我发现这个有用的例子提供了一个干净的实现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)));
      }
 }

我成功地测试了它:

@Test
public void testIsCompressed() {
    assertFalse(util.isCompressed(originalBytes));
    assertTrue(util.isCompressed(compressed));
}
于 2011-12-23T21:28:19.980 回答
11

我相信这是检查字节数组是否为 gzip 格式的最简单方法,它不依赖于任何 HTTP 实体或 mime 类型支持

public static boolean isGzipStream(byte[] bytes) {
      int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
      return (GZIPInputStream.GZIP_MAGIC == head);
}
于 2011-03-11T06:09:49.890 回答
5

基于@biziclop 的答案 - 此版本使用 GZIP_MAGIC 标头,另外对于空或单字节数据流是安全的。

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;
    }
}
于 2016-12-28T19:56:28.627 回答
4

此函数在Java中运行良好:

public static boolean isGZipped(File f) {   
    val raf = new RandomAccessFile(file, "r")
    return GZIPInputStream.GZIP_MAGIC == (raf.read() & 0xff | ((raf.read() << 8) & 0xff00))
}

斯卡拉

def isGZip(file:File): Boolean = {
   int gzip = 0
   RandomAccessFile raf = new RandomAccessFile(f, "r")
   gzip = raf.read() & 0xff | ((raf.read() << 8) & 0xff00)
   raf.close()
   return gzip == GZIPInputStream.GZIP_MAGIC
}
于 2016-08-22T13:21:58.757 回答
1

不完全是您所要求的,但如果您使用 HttpClient,则可能是另一种方法:

private static InputStream getInputStream(HttpEntity entity) throws IOException {
  Header encoding = entity.getContentEncoding(); 
  if (encoding != null) {
     if (encoding.getValue().equals("gzip") || encoding.getValue().equals("zip") ||      encoding.getValue().equals("application/x-gzip-compressed")) {
        return new GZIPInputStream(entity.getContent());
     }
  }
  return entity.getContent();
}
于 2011-01-27T15:54:40.640 回答
1

将原始流包装在 BufferedInputStream 中,然后将其包装在 GZipInputStream 中。接下来尝试提取一个 ZipEntry。如果这有效,它是一个 zip 文件。然后你可以在 BufferedInputStream 中使用“mark”和“reset”返回到流中的初始位置,在你检查之后。

于 2011-01-27T15:50:57.460 回答
1

SimpleMagic是一个用于解析内容类型的 Java 库:

<!-- pom.xml -->
    <dependency>
        <groupId>com.j256.simplemagic</groupId>
        <artifactId>simplemagic</artifactId>
        <version>1.8</version>
    </dependency>

import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.j256.simplemagic.ContentType;
// ...

public class SimpleMagicSmokeTest {

    private final static Logger log = LoggerFactory.getLogger(SimpleMagicSmokeTest.class);

    @Test
    public void smokeTestSimpleMagic() throws IOException {
        ContentInfoUtil util = new ContentInfoUtil();
        InputStream possibleGzipInputStream = getGzipInputStream();
        ContentInfo info = util.findMatch(possibleGzipInputStream);

        log.info( info.toString() );
        assertEquals( ContentType.GZIP, info.getContentType() );
    }
于 2016-09-28T16:59:22.090 回答
0

这是读取可以压缩的文件的方法:

private void read(final File file)
        throws IOException {
    InputStream stream = null;
    try (final InputStream inputStream = new FileInputStream(file);
            final BufferedInputStream bInputStream = new BufferedInputStream(inputStream);) {
        bInputStream.mark(1024);
        try {
            stream = new GZIPInputStream(bInputStream);
        } catch (final ZipException e) {
            // not gzipped OR not supported zip format
            bInputStream.reset();
            stream = bInputStream;
        }
        // USE STREAM HERE
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
于 2015-11-03T11:19:00.750 回答