mytechead

Android & Wordpress Help center

Archive for the month “January, 2014”

Android: Create a file and write to external storage

Here’s a quick tutorial on how to create a file and write it’s content to external storage:

Let’s first write a code that checks if external storage is available for READ / WRITE operations

/**

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

Post Navigation