Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
Answer from Nirav Ranpara on Stack Overflow
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - We can use Java NIO Channels or Java IO InputStream to read data from the URL open stream and then save it to file. Here is the simple java download file from URL example program. It shows both ways to download file from URL in java.
Top answer
1 of 16
95

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
2 of 16
72

Simple kotlin version

fun download(link: String, path: String) {
    URL(link).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

is there anyway to get the download progress or downloaded size from this method ?

This is the same realization as defined in InputStream.copyTo, but with progress

/*inline*/ fun download(link: String, path: String, progress: ((Long, Long) -> Unit)? = null): Long {
    val url = URL(link)
    val connection = url.openConnection()
    connection.connect()
    val length = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) connection.contentLengthLong else
        connection.contentLength.toLong()
    url.openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
            var bytesRead = input.read(buffer)
            var bytesCopied = 0L
            while (bytesRead >= 0) {
                output.write(buffer, 0, bytesRead)
                bytesCopied += bytesRead
                progress?.invoke(bytesCopied, length)
                bytesRead = input.read(buffer)
            }
            return bytesCopied
        }
    }
}

An example of usage:

val handler = object : Handler(Looper.getMainLooper()) {

    override fun handleMessage(msg: Message) {
        // length may be negative because it is based on http header
        val (progress, length) = msg.obj as Pair<Long, Long>
    }
}

// call this outside of main thread
val totalSize = download("http://example.site/path/to/file", "path/to/file") { progress, length ->
    // handling the result on main thread
    handler.sendMessage(handler.obtainMessage(0, progress to length))
}
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - Finally, weโ€™ll talk about how ... basic API we can use to download a file is Java IO. We can use the URL class to open a connection to the file we want to download....
๐ŸŒ
Java2s
java2s.com โ€บ example โ€บ android โ€บ java.net โ€บ download-file-from-url.html
download File from Url - Android java.net
c o m URL url = new URL(sUrl); int slashIndex = sUrl.lastIndexOf('/'); String fileName = sUrl.substring(slashIndex + 1); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // set up some things on the connection urlConnection.setRequestMethod("GET"); // http://stackoverflow.com/questions/9365829/filenotfoundexception-for-httpurlconnection-in-ice-cream-sandwich // urlConnection.setDoOutput(true); // and connect! urlConnection.connect(); // this will be used in reading the data from the internet InputStream inputStream = urlConnection.getInputStream(); // this is the total size of the file int totalSize = urlConnection.getContentLength(); // variable to store total downloaded bytes int downloadedSize = 0; // create a buffer...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ how-to-download-a-file-from-a-url-in-java
How to Download a File from a URL in Java
August 21, 2018 - As you can see we open up a connection using the URL object and then read it via the BufferedInputStreamReader object. The contents are read as bytes and copied to a file in the local directory using the FileOutputStream. To lower the number of lines of code we can use the Files class available ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ android โ€บ how-to-download-file-from-url-in-android-programmatically-using-download-manager
How to Download File from URL in Android Programmatically using Download Manager? - GeeksforGeeks
July 23, 2025 - <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/download" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Download Content" /> </LinearLayout> ... Go to the MainActivity.java file and refer to the following code.
๐ŸŒ
STechies
stechies.com โ€บ download-file-from-url-java
How to Download a File from a URL in Java
Within the try block, set the URL and the URLConnection using getInputStream(). The following catch block will handle any input-output exception and execute the printStackTrace(). The finally block (which executes automatically as a mandatory part of the program) will display the message โ€œURL's File downloaded.โ€ ยท Java NIO (abbreviated as New IO) is an alternative input-output Java API that also comes as a Java package.
Find elsewhere
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ how-to-download-part-of-file-url-android
How to Download a Specific Portion of a File from a URL in Android - CodingTechRoom
try { // URL of the file to be downloaded URL url = new URL("https://example.com/largefile.zip"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Specify the range of bytes to download connection.setRequestMethod("GET"); connection.setRequestProperty("Range", ...
๐ŸŒ
Mobikul
mobikul.com โ€บ home โ€บ how we download file from url in android
How we download File from URL in android - Mobikul
April 22, 2017 - There are many methods to download files from the server. ... Use DownLoadManager class and many others. I am discussing with DownLoadManager, it is applied on the GingerBread or above version of applications. GingerBread brought a new feature, DownloadManager, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system. ... Reference: http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog
๐ŸŒ
amitph
amitph.com โ€บ home โ€บ java โ€บ how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - HttpClient httpClient = ... Paths.get(outputPath));Code language: Java (java) First, we simply create an instance of HttpClient using its builder....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 31555827 โ€บ url-that-downloads-file-in-android
java - Url that downloads file in android - Stack Overflow
when I try to download the file using the following code I get the html file.. private class DownloadTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... sUrl) { InputStream input = null; OutputStream output = null; HttpURLConnection connection = null; String path = Environment.getExternalStorageDirectory().getPath() + "/" + sUrl[1]; Log.d(TAG, "PATH: " + path); try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ java โ€“ how to download a file from the internet
Java - How to download a file from the Internet - Mkyong.com
March 16, 2017 - package com.mkyong; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class HttpUtils { public static void main(String[] args) { String fromFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest"; String toFile = "F:\\arin.txt"; try { URL website = new URL(fromFile); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(toFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.
๐ŸŒ
ProxiesAPI
proxiesapi.com โ€บ articles โ€บ downloading-images-from-urls-in-java
Downloading Images from URLs in Java | ProxiesAPI
May 5, 2024 - We provide a filename to save the downloaded image. ... URL object with the image URL. ... HttpURLConnection to the URL and set the request method to "GET". ... InputStream from the connection to read the image data. ... FileOutputStream to write the image data to a file. We read the image data in chunks using a buffer and write it to the output stream. We close the streams and disconnect the connection. ... java.net.HttpURLConnection gives you more control over the HTTP connection and allows you to download images efficiently.
๐ŸŒ
Medium
pkslow.medium.com โ€บ multiple-ways-to-download-files-from-internet-in-java-ced5d3aaae2c
Multiple Ways to Download Files from Internet in Java | by Larry Deng | Medium
April 3, 2023 - We use BufferedInputStream to read and FileOutputStream to write to the local file: private static void javaIO() { try { try (BufferedInputStream in = new BufferedInputStream(new URL(URL).openStream()); FileOutputStream fileOutputStream = new ...
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ java-android-program-download-file-service
How to Download File using Service in Android? - Sanfoundry
June 16, 2022 - package com.example.download_file_service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import android.app.Activity; import android.app.IntentService; import android.content.Intent; import android.os.Environment; public class DownloadService extends IntentService { private int result = Activity.RESULT_CANCELED; public static final String URL = "urlpath"; public static final String FILENAME = "filename"; public static final String FILEPATH = "filepath"; public static final String RESULT = "result"; public static final String NOTIFICATION = "service receiver"; public DownloadService() { super("DownloadService"); } // Will be called asynchronously by OS.
๐ŸŒ
codippa
codippa.com โ€บ home โ€บ download file from url in java
Java - Download file from a URL in 3 ways
January 12, 2025 - This approach is based on the following steps. Create a connection to the given file url. Get input stream from the connection. This stream can be used to read file contents. Create an output stream to the file to be downloaded.
Top answer
1 of 2
4

You are declaring DownloadFile object but not initializing it.

private DownloadFile df;
df.Download(); // Throws NPE

Don't forget to initialize it.

private DownloadFile df = new DownloadFile();
df.Download();

EDIT:

Now you initialised the object and avoided NPE but this time you are getting a NetworkOnMainThreadException. After Honeycomb version, Android does not allow you to do network operations on main thread. You can use an AsyncTask to overcome this.

2 of 2
0

In Kotlin, This function can be useful, here try/catch avoids crash and handle send Toast to user.

After that maybe need UNZIP this file, so please see this link https://stackoverflow.com/a/76032406/12272687

fun downloadZip() {


        val url = URL("http://www.Any.com/sub/name.zip")

        Thread {
            try {
                val con: HttpURLConnection = url.openConnection() as HttpURLConnection
                con.doInput = true
                con.connectTimeout = 1200
                con.connect()
                val responseCode = con.responseCode
               

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    val m = con.inputStream
                    val inStream = BufferedInputStream(m, 1024 * 5)
                    val myFilename = "newFile"
                    val myExtensionVar = ".zip"
                    val file = File(
                        context.getDir("Music", AppCompatActivity.MODE_PRIVATE),
                        "/$myFilename$myExtensionVar"
                    )
                    
                    Log.i("well", "Downloaded file: $file")
                    if (file.exists()) {
                       file.delete()
                       
                    }else{
                    val buff = ByteArray(5 * 1024)
                    // Create File (Copy)
                    file.createNewFile()
                    val outStream = FileOutputStream(file)
                    var len:Int
                    while (inStream.read(buff).also { len = it } >= 0) {

                        outStream.write(buff, 0, len)


                    }

                    outStream.flush()
                    outStream.close()
                    inStream.close()
                    Log.i("well", "Done file: $file")

                    handler.post {
                        Toast.makeText(
                            context,
                            context.getString(R.string.mes_end_file), Toast.LENGTH_SHORT
                        ).show()
                      

                      
                    }
                    }
                }
            } catch (ex: Exception) {
                ex.printStackTrace()
                handler.sendMessage(handler.obtainMessage(22, "OK"))
            } catch (ex: IllegalThreadStateException){
                println( ex.printStackTrace())
                handler.sendMessage(handler.obtainMessage(22, "OK"))
            }

        }.start()
๐ŸŒ
TutorialKart
tutorialkart.com โ€บ java โ€บ java-download-file-from-url
How to Download File from URL in Java?
January 10, 2023 - In this example, we will download an image from URL and save it in our local file system. ... import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; /** * Java Example Program to download an image from URL */ public class DownloadFromURL { public static void main(String[] args) { try { URL url = new URL("https://www.tutorialkart.com/img/tutorials.png"); File destination_file = new File("files/tutorials.png"); FileUtils.copyURLToFile(url, destination_file); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }