Search code examples
javanio

How to download a file from a website?


I was looking for a way to download a file from a website. I've seen this question (How to download and save a file from Internet using Java?) already, but I was wondering if you could clear two things up for me. First, let's say the link to the file is "http://www.mediafire.com/download/fasd13z88k7umvm/SecurityCraft+v1.4pre+for+1.6.4.zip". I would insert the link in the URL constructor:

String url = "http://www.mediafire.com/download/fasd13z88k7umvm/SecurityCraft+v1.4pre+for+1.6.4.zip";
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

but what needs to be inserted in the FileOutputStream constructor? And the second thing is, where would fos.getChannel().transferFrom() save the file to? Or do I need to do another step to save the file to my hard drive?

Anyway, thanks for reading.


Solution

  • In answer to your first question, you put the filename of where you want to save the file. See the docs here.. And I think that answers your second question, since the string is where you want to save the file.

    Just remember if you use a relative path, the file will save where the application is executed, and you also need to make sure you have write access to that directory.