Write a File to SDCard

Frequently used code samples and tutorials
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Write a File to SDCard

Postby vivekkalady » Fri Nov 21, 2014 5:45 pm

This code shows how to write a file to SDCard

Add this permission to manifest

Code: Select all

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

Check availability of external storage

Code: Select all

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

Code: Select all

// 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");


File Output Stream

Code: Select all

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
// 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”;

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest