First of all, sorry for my bad english, is not my first language. I'm coding a method that downloads a file from internet. I know there are several ways to do that, but my issue is still happening , no matter what method I use.
The code should download a .torrent file, and it does, but the "final" file seems to be corrupted. Let me guide you through the following pictures:
a common torrent file downloaded from the web (using a navigator)
the same torrent file, but downloaded from my java code
The download process goes wrong, as far as I concern. I tried the following two ways and both of them download the same "encoded" thing.
Possible solution #1 - java.nio
//Get .torrent file
public void getTorrentFile(String torrentURL, String fileName) {
try {
URL website = new URL(torrentURL);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (MalformedURLException mue) { mue.printStackTrace(); }
catch (IOException ioe) {
ioe.printStackTrace(); }
}
}
*Possible solution #2 - The loop *
File torrentFile = new File(fileName);
URLConnection conn = new URL(torrentURL).openConnection();
conn.connect();
try (InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(torrentFile)) {
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
} catch (IOException ioe) { ioe.printStackTrace(); }
} catch (IOException ioe) { ioe.printStackTrace(); }
As I said before, this 2 solutions are wrong. They are useful to download a file, but some of the torrents that I want to download, come corrupt.
Why does my file comes "corrupt" to my pc? Thanks in advance.