views:

447

answers:

1

Using the guide at Android Developers (http://developer.android.com/guide/topics/data/data-storage.html) I've tried to store some data to the SD-Card. This is my code:

    // Path to write files to
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                  "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
    String fname = "mytest.txt";

    // Current state of the external media
    String extState = Environment.getExternalStorageState();

    // External media can be written onto
    if (extState.equals(Environment.MEDIA_MOUNTED))
    {
        try {
            // Make sure the path exists
            boolean exists = (new File(path)).exists();  
            if (!exists){ new File(path).mkdirs(); }  

            // Open output stream
            FileOutputStream fOut = new FileOutputStream(path + fname);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory. Can anyone tell me what I'm doing wrong? I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".

+4  A: 

Have you given your application permission to write to the SD Card?

You do this by adding the following to your AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Dave Webb
Its the simple things that make the big difference... Thanks! =)
BBoom
Ahh thank you so much! Damn manifest always gets me.
mxrider