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?
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);
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.
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).
Use Apache Commons IO. It is just one line of code:
FileUtils.copyURLToFile(URL, File)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With