TranquilMarmot
TranquilMarmot

Reputation: 2314

Can't write to external storage on Android

I see a bunch of other people asking this same question, but none of the solutions posted helped me.

I'm trying to write a (binary) file to external storage from my Android app. I put <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> into my manifest, but I still can't manage to create any files. The code I'm using to create files is

File folder = new File(Environment.getExternalStorageDirectory(), SAVE_DIRECTORY);
File toWrite = new File(folder, "save.bin");
if(!toWrite.exists()){
    try {
        if(!folder.mkdirs())
            Log.e("Save", "Failed to create directories for save file!");
        toWrite.createNewFile();
     } catch (IOException e) {
         Log.e("Save", "Failed to create save file! " + e.getMessage());
     }
 }

The call to mkdirs() fails, and the createNewFile() throws the IOException (ENOENT, because the directory doesn't exist)

Anybody know what's up? I've even tried rebooting my device. I'm on API level 8 on a Nexus 7, if it makes any difference.

Upvotes: 2

Views: 7545

Answers (3)

narko
narko

Reputation: 3885

I was suffering this issue as well and everything was properly configured in my app, i.e., I had the read and write permissions for external storage.

My problem was in the way I was creating the path to store my files:

private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "myFolder"

Note that it is necessary to include the "/" as follows:

private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "/myFolder/"

Without this, you won't be able to create the folder. Android won't fail, so you might think that there are issues with your phone configuration or app permissions.

Ideally, this helps somebody to save some precious time.

Upvotes: 1

KGBird
KGBird

Reputation: 799

The documentation says that starting in API level 19, WRITE_EXTERNAL_STORAGE is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir(). However if you don't want to write files there and instead want to write files to getExternalStorageDirectory(), under API 23 or higher you have to request permission at run time using requestPermissions(). Once I did that I was able to create a directory in getExternalStorageDirectory().

Upvotes: 2

tesla1984
tesla1984

Reputation: 541

first you should check the ExternalStorageState

public static boolean isSDCARDAvailable(){
   return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}

if this method isSDCARDAvailable return true, then use your code

add the permissions:

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

Upvotes: 5

Related Questions