86

I am using the following code to download a file from my server then write it to the root directory of the SD card, it all works fine:

package com.downloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class Downloader {

    public void DownloadFile(String fileURL, String fileName) {
        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            FileOutputStream f = new FileOutputStream(new File(root, fileName));

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }

    }
}

However, using Environment.getExternalStorageDirectory(); means that the file will always write to the root /mnt/sdcard. Is it possible to specify a certain folder to write the file to?

For example: /mnt/sdcard/myapp/downloads

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
RailsSon
  • 19,897
  • 31
  • 82
  • 105

4 Answers4

164
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
plugmind
  • 7,926
  • 4
  • 34
  • 39
  • 1
    Make sure to use all lower case letters in your directory and file names. – BeccaP Nov 13 '13 at 15:41
  • 1
    May i know what does it meant by "/dir1/dir2" and without this i can't save my file in sdcard ah? – AndroidOptimist Nov 15 '13 at 06:46
  • 18
    According to doc: *Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). **Traditionally this is an SD card**, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer* – mr5 Oct 01 '15 at 06:11
  • 1
    @NeonWarge [see here](https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()) – mr5 Jul 16 '18 at 01:47
  • Warning: `getExternalStorageDirectory()` was deprecated in API 29. – Josh Correia Jul 09 '20 at 23:20
33

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();
hcpl
  • 17,382
  • 7
  • 72
  • 73
  • 2
    The authors of the book I'm reading recommends to use a `FileOutputStream` (well, it doesn't cover the alternatives). Why is it better to use the `FileWriter` instead - is it faster/more reliable/something else? – aga Feb 05 '14 at 18:42
  • 3
    @aga `FileWriter` has convenience methods for directly writing Strings, which aren't present on a `FileOutputStream`. If you aren't writing text files, `FileWriter` isn't much help. In fact, if you're writing an *image* file, it can't really be done at all with a `FileWriter` Of course, if you *really* want a nice API for text, wrap your `FileOutputStream` in a `PrintStream` and you'll have all the same methods as `System.out`. – Ian McLaird Oct 09 '14 at 13:38
  • 1
    why can't I find the file on my sdcard after the file is successfully written ? – Someone Somewhere Aug 09 '18 at 21:36
2

Found the answer here - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/

It says,

/**

* Method to check if user has permissions to write on external storage or not

*/

public static boolean canWriteOnExternalStorage() {
   // get the state of your external storage
   String state = Environment.getExternalStorageState();
   if (Environment.MEDIA_MOUNTED.equals(state)) {
    // if storage is mounted return true
      Log.v("sTag", "Yes, can write to external storage.");
      return true;
   }
   return false;
}

and then let’s use this code to actually write to the external storage:

// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();

And this is it. If now you visit your /sdcard/your-dir-name/ folder you will see a file named - My-File-Name.txt with the content as specified in the code.

PS:- You need the following permission -

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
coffeemakr
  • 330
  • 2
  • 12
alchemist
  • 1,081
  • 12
  • 17
-1

In order to download a file to Download or Music Folder In SDCard

File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES

And dont forget to add these permission in manifest

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300