Download file from URL android programmatically

Today we will learn how to download a file from URL in java. We can use java.net.URL openStream() method to download file from URL in java program. We can use Java NIO Channels or Java IO InputStream to read data from the URL open stream and then save it to file.

Java Download File from URL

Download file from URL android programmatically
Here is the simple java download file from URL example program. It shows both ways to download file from URL in java. JavaDownloadFileFromURL.java

package com.journaldev.files;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class JavaDownloadFileFromURL {

    public static void main(String[] args) {
        String url = "https://www.journaldev.com/sitemap.xml";
        
        try {
            downloadUsingNIO(url, "/Users/pankaj/sitemap.xml");
            
            downloadUsingStream(url, "/Users/pankaj/sitemap_stream.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadUsingStream(String urlStr, String file) throws IOException{
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count=0;
        while((count = bis.read(buffer,0,1024)) != -1)
        {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    private static void downloadUsingNIO(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}

downloadUsingStream: In this method of java download file from URL, we are using URL openStream method to create the input stream. Then we are using a file output stream to read data from the input stream and write to the file. downloadUsingNIO: In this download file from URL method, we are creating byte channel from URL stream data. Then use the file output stream to write it to file. You can use any of these methods to download the file from URL in java program. If you are looking for performance, then do some analysis by using both methods and see what suits your need.

You can checkout more Java IO examples from our GitHub Repository.

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

importjava.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

}

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.

importjava.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

}

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

importjava.io.BufferedInputStream

import java.io.FileOutputStream

importjava.net.URL

fun downloadFile(url:URL,fileName: String){

    url.openStream().use{inp->

        BufferedInputStream(inp).use{bis ->

            FileOutputStream(fileName).use {fos->

                val data =ByteArray(1024)

                varcount:Int

                while (bis.read(data,0, 1024).also{count=it}!=-1){

                    fos.write(data,0,count)

                }

            }

        }

    }

}

fun main(){

    // call `downloadFile()` function

}

Download Code

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

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)


How to get download file in Android Programmatically?

Step by Step Implementation.
Step 1: Create a New Project. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. ... .
Step 2: Grant internet permission in the AndroidManifest.xml file. ... .
Step 3: Working with the activity_main.xml file..

How to download file from URL in Android Programmatically Kotlin?

Download file from remote URL in Kotlin.
Using FileChannel. transferFrom() function. ... .
Using Files. copy() function. ... .
Using BufferedInputStream. Finally, we can read the file from the input stream byte-by-byte and write the bytes to a file output stream..

How do I download from URL?

Save the file:.
Most files: Click on the download link. Or, right-click on the file and choose Save as..
Images: Right-click on the image and choose Save Image As..
Videos: Point to the video. Click Download. . ... .
PDFs: Right-click on the file and choose Save Link As..
Webpages: At the top right, click More. More Tools..
Go to the webpage where you want to download a file. Touch and hold what you want to download, then tap Download link or Download image.