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
Cheers
Eef
In order to download a file to Download or Music Folder In SDCard
And dont forget to add these permission in manifest
Add Permission to Android Manifest
Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.
Check availability of external storage
You should always check for availability first. A snippet from the official android documentation on external storage.
Use a Filewriter
At last but not least forget about the
FileOutputStream
and use aFileWriter
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.Found the answer here - http://mytechead.wordpress.com/2014/01/30/android-create-a-file-and-write-to-external-storage/
It says,
and then let’s use this code to actually write to the external storage:
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 -