Why can i not make a directory inside Environment.

2019-06-21 10:58发布

问题:

This is my code

File selfieLocation = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
               "Daily Selfies");
boolean isDirectory = false;
if(!selfieLocation.isDirectory()) {
        //Creates directory named by this file
        selfieLocation.mkdir();
        isDirectory = selfieLocation.isDirectory();
 }
 //array of strings 
 for(String selfiePath: selfieLocation.list()) {
        selfies.add(selfiePath);
 }

Basically what I am trying to do is create my own customizable directory inside of the standard directory in which to place pictures that are available to the user.

I looked at related threads and saw this one, Android: unable to create a directory in default pictures folder. However I made sure that I had a call to getExternal...., and not just have Environment.DIRECTORY_PICTURES as a parameter. I also looked on here http://developer.android.com/guide/topics/data/data-storage.html#filesExternal and saw that I had the right method call/format to create a customizable folder in external memory. The docs example was

File file = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
    Log.e(LOG_TAG, "Directory not created");
}

I stepped through my code and saw that the local variable isDirectory stayed at false even after the call to selfieLocation.mkdir(). Does anyone know why this directory cannot be created?

回答1:

Try to create directory with File#mkdirs(), not File#mkdir(). The latter assumes that all parent directories are already in place, so it won't create directory if any of its parents don't exist.
Also, take a look at your permissions in AndroidManifest.xml. You need the following permissions in order to read/write the content on external storage:

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

android.permission.READ_EXTERNAL_STORAGE isn't required for now, but it will be in the future releases of Android.