java - 如何检查 InputStream 是否已压缩?

标签 java http gzip inputstream httpurlconnection

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

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;

}

最佳答案

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

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

(魔数(Magic Number)来源:GZip file format specification)

更新:我刚刚发现 GZipInputStream 中还有一个名为 GZIP_MAGIC 的常量包含这个值,所以如果你 < strong>真的想要,可以用低两个字节吧。

关于java - 如何检查 InputStream 是否已压缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4818468/

相关文章:

python - 这是这个 gzip inflate 方法中的错误吗?

javascript - Gzip 适用于 html,但不适用于 javascript 或 css (Apache)

java - 如何仅使用注解将相同类型的bean组合到一个数组中?

iphone - 跨 View Controller 共享 NSOperationQueue?

linux - 多 cpu 核心 gzip 一个大文件

c# - ASP.NET WebApi - 如何将集合发布到 WebApi 方法?

windows - 在 IIS 中禁用匿名访问是否会带来安全风险?

java - 有谁知道 NetBeans 6.x 是否可以与 Leopard 上的 Java SE 6 一起使用?

java - AWS Lambda 在图层中找不到共享对象文件

java - Android:上传文件和填写POST正文一起