Friday, December 16, 2011

Saving files to External Storage in Android


Just a snippet of code for android that can help some of my friends.
String FILENAME = "myfile.txt";
boolean externalStorageMounted = false;
boolean externalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
 externalStorageMounted = true;
 externalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
 externalStorageMounted = true;
 externalStorageWriteable = false;
} else {
 externalStorageMounted = false;
 externalStorageWriteable = false;
}

if (externalStorageMounted && externalStorageWriteable) {
 File dbfile = new File(Environment.getExternalStorageDirectory(), FILENAME);
 FileOutputStream fos = new FileOutputStream(dbfile, true);
 //Do anything with fos
 try {
  if (fos != null)
   fos.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
}
Ok, almost done, but not yet.Open your AndroidManifest.xml and add the following line

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

or  using graphical interface: Permissions -> Add... -> android.permission.WRITE_EXTERNAL_STORAGE

And everything ready.

No comments:

Post a Comment