Download file from remote URL in Kotlin
This post will discuss how to download a file from a remote URL in Kotlin.
1. Using FileChannel.transferFrom() function
The FileChannel#transferFrom() function is used to transfer bytes into this channel’s file from a readable byte channel. It accepts three parameters – the source channel, the position within the file to begin the transfer, and the maximum number of bytes to be transferred.
Its usage is demonstrated below using the use() function, which takes care of closing the opened streams and channels.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.FileOutputStream import java.net.URL import java.nio.channels.Channels fun downloadFile(url: URL, outputFileName: String) { url.openStream().use { Channels.newChannel(it).use { rbc -> FileOutputStream(outputFileName).use { fos -> fos.channel.transferFrom(rbc, 0, Long.MAX_VALUE) } } } } fun main() { // call `downloadFile()` function } |
2. Using Files.copy() function
We can also use the Files.copy() function to copy all bytes from an input stream to a file. It takes the input stream to read from and the path to the file and optional params indicating how copying should be done.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.net.URL import java.nio.file.Files import java.nio.file.Paths fun downloadFile(url: URL, fileName: String) { url.openStream().use { Files.copy(it, Paths.get(fileName)) } } fun main() { // call `downloadFile()` function } |
3. Using BufferedInputStream
Finally, we can read the file from the input stream byte-by-byte and write the bytes to a file output stream. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.BufferedInputStream import java.io.FileOutputStream import java.net.URL fun downloadFile(url: URL, fileName: String) { url.openStream().use { inp -> BufferedInputStream(inp).use { bis -> FileOutputStream(fileName).use { fos -> val data = ByteArray(1024) var count: Int while (bis.read(data, 0, 1024).also { count = it } != -1) { fos.write(data, 0, count) } } } } } fun main() { // call `downloadFile()` function } |
That’s all about downloading a file from a remote URL in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)