How to:‎ > ‎

Save File to SD Card

In order to save a file to the SD card you must have permissions to write to the card. You need to add the following to your AndroidManifest.xml:

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

Next you open a file stream, write to it, and close it wherever you want to do that in code:

String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
    fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    // handle exception
} catch (IOException e) {
    // handle exception

Note: you with get a FileNotFoundException if you try to open/create a file on the SD card when it is mounted on your computer. You must unmount it first before you can access it in your application.