Permission denied when writing into sdCard

天大地大妈咪最大 提交于 2019-11-29 10:06:29

For writing to the Sdcard you need to give the permission in your manifest file

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

You need to make sure you have the permission @Ram mentions, and the SD Card is mounted. You can check if it is mounted by:-

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))

You should handle an unmounted card gracefully, but a common gotcha is if your phone is plugged in via the USB cable you may have it mounted via your desktop OS, which means it's not mounted by Android.

Thanks,

Ryan

Hades

Here's a bit of code I use,

public void yourMethod(){

File root = getDir(getApplicationContext());     
    try {  
        File fileDir = new File(root.getAbsolutePath()+"/fun/");  
        fileDir.mkdirs();  

        File file = new File(fileDir, "itisfun.txt");  
        FileWriter filewriter = new FileWriter(file);  
        BufferedWriter out = new BufferedWriter(filewriter);  
        out.write("I m enjoying......dude");  
        out.close();

    } catch(...) {
    ...
    }
}


public File getDir(Context context) {

        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(
                    android.os.Environment.getExternalStorageDirectory(),
                        DIRECTORY_NAME);
        else
            cacheDir = context.getCacheDir();
        return cacheDir;
    }

If there is no external storage, it basically uses the phones internal cache (not good for large files)

Read this

If you're on 4.4, read here: http://www.androidcentral.com/kitkat-sdcard-changes Basically you can no longer read and write anywhere on the drive. You can only write to your private directory and directories you've become the owner of.

  1. Check that your directory fun and the file itisfun.txt exists on the SDcard, if you want to make them by program, you have to add the permission:
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    This permission allows the application to create file or directory, the permission:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> only allows the application to read and write the file that is already exist.
  2. Make sure that your permission is outside of the <application> tag, usually before it.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!