Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Premission denied when trying to save file to sd card

Im trying to save a textfile to the sd card but i am getting the Eacess (permission deined) error. My code looks as following:

      try {
            File myFile = new File(Environment.getExternalStorageDirectory().getPath() + "/myfile");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(text.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

I have already allowed the `

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

in the android manifest

Ive been looking at some other posts relating this issues but nothing solved it.

What am i missing?

Update my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.files"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />   
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.files.FilesActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Upvotes: 1

Views: 245

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006674

To save files to external storage, it helps to have external storage. :-)

Unfortunately, the AVD Manager defaults to having no external storage (even though I have suggested that they change this). So, if you are using an emulator, double-check to make sure that you have filled in a value for the "SD Card" size.

I usually allocate something small, like 32MB -- enough that you can work with external storage, not so much that it chews up a bunch of your hard drive or slows down the initial AVD launch. Of course, if you are planning on testing something that needs a lot more external storage than that, pick a value that suits.

Upvotes: 2

Related Questions