Question

I'm trying to download .torrent files from the internet. Some of the files online are compressed (gzipped) format. I know I can unzip the files with the following code:

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

but some of the .torrent files are not compressed and I therefore get the error message:

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

I'm dealing with a large database of .torrent files so I can't unzip them 1 by 1 if it is compressed. How do I know whether the .torrent file is compressed or not and only unzip the file if it is compressed?

Pseudo Code:

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

SOLUTION:

    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();
    }
Was it helpful?

Solution

You can use a BufferedInputStream. It is likely to be a good idea in any case. This will allow you to mark() the start and attempt to uncompress the data and if it fails, reset() the stream and read it normally. (more efficiently, all GZIP files start with the same two bytes) ;)

All GZIP streams start with bytes 1f 8b http://en.wikipedia.org/wiki/Gzip

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top