在Java中如何实现Gzip的完整性校验(类似gzip -t <file> 命令)?
已解决:
GZIPInputStream+FileOutputStream会自己检查是否完整,不完整会直接抛ZipException
/**
* 解压GZIP
*
* @param input
* @param output
* @throws IOException
*/
public static void decompressGzip(File input, File output) throws IOException, ZipException {
try (GZIPInputStream in = new GZIPInputStream(new FileInputStream(input))) {
try (FileOutputStream out = new FileOutputStream(output)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
}
}
gzip,zip, rar这一类的test命令的算法似乎是解压缩到
/dev/null
,判断是否有错误来决定的,由于不直接写入磁盘IO,所以速度极快。所以如果你要实现它的算法你也可以这么干。Java 中使用
null
设备的输出流为OutputStream.nullOutputStream()
(Java >= 11),所以你将gzip数据流输出到这个流中,检查是否抛出异常就行了