Hi everyone,

I'm using the following code snippet to download and save a file from an address using Java...

URL website = new URL("http://www.website.com/example.torrent");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("example.torrent");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);

However, a problem occurs when I try to download a file with the extension ".torrent". After downloading a torrent file, when I click on that file, Bittorrent gives me the following error...

"example.torrent" is not valid bencoding.

I think, in a way, torrent file become changed or broken during download. Is there a solution for it, or is there something wrong in the code snippet above?

Thank you in advance.

Is that code working fine for other file extensions??

The documentation for transferFrom doesn't seem to promise that it will get your entire file. It says that there are situations where it will only read some of the requested bytes and you are clearly depending on that since I doubt you really want 1 << 24 bytes. You must be assuming that the number of bytes that actually get transfered will always be the size of the file and not less, but do you have proof that's true?

Have you checked that the file you get is the correct size? Perhaps you are only getting the beginning of the file. I think you should only use transferFrom if you know how many bytes you want. It clearly seems designed for people who know that. What happens if you just use your website.openStream directly? At least then you would know for certain when you reach the end of the file.

@bguild Thanks. I will check that.

@bguild I checked what you said. The third parameter which the method "transferFrom" gets is the maximum number of bytes which you allow. Even if I write bigger number than the size of the torrent file I tried to download, it does not still work. I could not figure out. Is there a possibility that the transferFrom() changes the nature of torrent file?