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.

Download Code

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.

Download Code

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:

Download Code

That’s all about downloading a file from a remote URL in Kotlin.