如何检查InputStream是否被Gzip化? [英] How to check if InputStream is Gzipped?
问题描述
有没有办法检查InputStream是否已被gzip压缩?
这是代码:
Is there any way to check if InputStream has been gzipped? Here's the code:
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;
}
}
我试过这种方式,但它不起作用expected - 从流中读取的值无效。
编辑:
添加了我用来压缩数据的方法:
I tried this way but it doesn't work as expected - values read from the stream are invalid. Added the method I use to compress data:
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也以一个神奇的数字开头,可以在不读取整个流的情况下快速检查。
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;
}
(幻数的来源: GZip文件格式规范)
更新:我刚刚发现在 GZipInputStream
中还有一个名为 GZIP_MAGIC
的常量,其中包含这个值,所以如果你真的想要,你可以使用它的低两个字节。
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.
这篇关于如何检查InputStream是否被Gzip化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!