Android: read from or write to sdcard
May 09, 2011 11:55:27 Last update: May 09, 2011 11:55:27
Reading from or writing to sdcard isn't any different from normal Java io operations. Just use Java io to open the file then read from or write to it. Android does provide some utility methods to lookup directories under the sdcard. Examples:
Example
To write to sdcard:
// import android.os.environment File extDir1 = Environment.getExternalStorageDirectory(); Log.d("Test", "External storage dir from Environment: " + extDir1); File extDir2 = Environment.getExternalStoragePublicDirectory("AnyStringExceptNull"); Log.d("Test", "External storage public dir from Environment: " + extDir2); File extDir3 = getExternalFilesDir(null); Log.d("Test", "External storage dir (root) from Context: " + extDir3); File extDir4 = getExternalFilesDir(Environment.DIRECTORY_MUSIC); Log.d("Test", "External storage dir (Music) from Context: " + extDir4); File extDir5 = getExternalFilesDir("MyOwnType"); Log.d("Test", "External storage dir (MyOwnType) from Context: " + extDir5);
Example
logcat output:
D/Test ( 1353): External storage dir from Environment: /mnt/sdcard D/Test ( 1353): External storage public dir from Environment: /mnt/sdcard/AnyStringExceptNull D/Test ( 1353): External storage dir (root) from Context: /mnt/sdcard/Android/data/com.android.test/files D/Test ( 1353): External storage dir (Music) from Context: /mnt/sdcard/Android/data/com.android.test/files/Music D/Test ( 1353): External storage dir (MyOwnType) from Context: /mnt/sdcard/Android/data/com.android.test/files/MyOwnType
To write to sdcard:
try { FileWriter out = new FileWriter(new File(extDir1, "test.txt")); out.write("Writing test!"); out.close(); } catch (IOException e) { Log.e("Test", "What? " + e); }