Stack Overflow archive
2 scoreaccepted

How to download a file in Android

score
2
question views
959
license
CC BY-SA 3.0

You cannot download a file into "assets" or "/res/raw". Those get compiled into your APK.

You can download the file to your apps internal data directories. See Saving Files | Android Developers.

There are plenty of examples and libraries to help you with the download. The following is a static factory method you could use in your project:

java
public static void download(String url, File file) throws MalformedURLException, IOException {
    URLConnection ucon = new URL(url).openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection) ucon;
    int responseCode = httpConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        bis.close();
    }
}

Then, to download a file from Dropbox:

java
String url = "https://dl.dropboxusercontent.com/u/27262221/test.txt";
File file = new File(getFilesDir(), "test.txt");
try {
    download(url, file);
} catch (MalformedURLException e) {
    // TODO handle error
} catch (IOException e) {
    // TODO handle error
}

Please note that the above code should be run from a background thread or you will get a NetworkOnMainThreadException.

You will also need to declare the following permission in your AndroidManifest:

xml
<uses-permission android:name="android.permission.INTERNET" />

You can find some helpful libraries here: https://android-arsenal.com/free

I personally recommend http-request. You could download your dropbox file with HttpRequest like this:

java
HttpRequest.get("https://dl.dropboxusercontent.com/u/27262221/test.txt").receive(
    new File(getFilesDir(), "test.txt"));

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.