Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download and save a file from the Internet using Java?

Tags:

java

download

There is an online file (such as http://www.example.com/information.asp) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?

like image 560
echoblaze Avatar asked May 28 '09 14:05

echoblaze


People also ask

How do I download a text file in Java?

We will use the copy(inputStream, fileOS) method to download a file into the local system. InputStream inputStream = new URL("http://example.com/my-file-path.txt").openStream(); FileOutputStream fileOS = new FileOutputStream("/Users/username/Documents/file_name. txt"); int i = IOUtils. copy(inpuStream, fileOS);

How do I download a file with FileOutputStream?

FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME); FileChannel fileChannel = fileOutputStream. getChannel(); We'll use the transferFrom() method from the ReadableByteChannel class to download the bytes from the given URL to our FileChannel: fileOutputStream.


2 Answers

Give Java NIO a try:

URL website = new URL("http://www.website.com/information.asp"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("information.html"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Check more about it here.

Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.MAX_VALUE will transfer at most 2^31 bytes, Long.MAX_VALUE will allow at most 2^63 bytes (larger than any file in existence).

like image 122
dfa Avatar answered Sep 19 '22 13:09

dfa


Use Apache Commons IO. It is just one line of code:

FileUtils.copyURLToFile(URL, File) 
like image 38
卢声远 Shengyuan Lu Avatar answered Sep 18 '22 13:09

卢声远 Shengyuan Lu