gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:32:57 25 4
gpt4 key购买 nike

有什么方法可以检查 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com