Android MKDirs() not working for me - NOT EXTERNAL Storage

北慕城南 提交于 2019-12-11 10:33:58

问题


I have read over the various other postings on this and have not yet found an answer that is working for me. They have been discussing the use of External Storage and I need to use 'default' (internal) storage.

I have a very simple routine in one of my Activity routines

String PATH = "/data/data/com.mydomain.myapplicationname/files";
SystemIOFile.MkDir(PATH);  // Ensure Recipient Path Exists

And then in my SystemIOFile class I have

static public Boolean MkDir(String directoryName) 
  {
    Boolean isDirectoryFound = false;
    File Dir = new File(directoryName);
    if(Dir.isDirectory())
    {
      isDirectoryFound = true;
    } else {
      Dir.mkdirs();
      if (Dir.isDirectory()) 
      {
         isDirectoryFound = true;
      }
  }
  Dir = null;
  return isDirectoryFound;
}

And in my Android.Manifest.xml I have

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

So it seems as though all of the pieces are in place for this to work.

BUT it is not working.
When I single step through the MKDir() routine it ALWAYS fails.
The

if (Dir.isDirectory())

always returns false
And the subsequent Dir.mkdirs() always returns false

What am I missing?


回答1:


This is a great question. First, it's better if you don't reference the /sdcard path directly. Use Environment.getExternalStorageDirectory().getPath() instead. Second, assuming you want to access your own app's files - you also don't want to reference the /data/data path directly because it can vary in multi-user scenarios. Use Context.getFilesDir().getPath() instead.

Implementing the above, we see that:

String PATH = "/data/data/com.mydomain.myapplicationname/files";
SystemIOFile.MkDir(PATH);

Returns false, whereas:

String PATH = Environment.getExternalStorageDirectory().getPath() 
        + getApplicationContext().getFilesDir().getPath();
SystemIOFile.MkDir(PATH);

Returns true.

Also note that you ignored the result of Dir.mkdirs() inside Boolean MkDir(String directoryName) .

Hope this helps.




回答2:


"/data/data/com.mydomain.myapplicationname/files"

is not an external storage path. What you need to do is grab your application's allocated storage path.

Context c = /*get your context here*/;
File path = new File(c.getExternalFilesDir().getPath() + "/folder1/folder2/");
path.mkdirs();

If you need to access the app's internal filespace (provided the app accessing the space owns it) then you can use the Context's getFilesDir(). This will return the internal storage location of the app.

The code is essentially the same:

Context c = /*get your context here*/;
File path = new File(c.getFilesDir().getPath() + "/folder1/folder2/"); //this line changes
path.mkdirs();


来源:https://stackoverflow.com/questions/32055815/android-mkdirs-not-working-for-me-not-external-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!