不是 GZIP 格式的 Java



我正在尝试从互联网上下载.torrent文件。一些在线文件是压缩(gzipped)格式。我知道我可以使用以下代码解压缩文件:

    try (InputStream is = new GZIPInputStream(website.openStream())) {
        Files.copy(is, Paths.get(path));
        is.close();
    }

但是某些.torrent文件未压缩,因此我收到错误消息:

java.util.zip.ZipException: Not in GZIP format

我正在处理一个包含.torrent文件的大型数据库,因此如果压缩,我无法逐一解压缩它们。我如何知道.torrent文件是否已压缩,并且仅在压缩文件时才解压缩文件?

伪代码:

if(file is compressed){
unzip
download
}else{
download

溶液:

    try (InputStream is = new GZIPInputStream(website.openStream())) {
        Files.copy(is, Paths.get(path + "GZIP.torrent"));
        is.close();
    } catch (ZipException z) {
        File f = new File(path + ".torrent");
        FileOutputStream fos = new FileOutputStream(f);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
    }
您可以使用

BufferedInputStream。 无论如何,这可能是一个好主意。 这将允许您标记()开始并尝试解压缩数据,如果失败,则重置()流并正常读取。 (更高效,所有 GZIP 文件都以相同的两个字节开头) ;)

所有 GZIP 流都以字节 1f 8b http://en.wikipedia.org/wiki/Gzip 开头

最新更新