Mkdirs does not create folder in internal storage (Android)

Bouss picture Bouss · Dec 27, 2014 · Viewed 11.9k times · Source

I'm trying to create a folder in the internal storage of an app so I can download files to it. But it doesn't seem to work. I've been looking for a solution for hours and hours but I can't find one and it's starting to drive me crzay.

This the code to create the folder:

String intStorageDirectory = Environment.getDataDirectory().toString();
File folder = new File(intStorageDirectory, "testthreepdf");
folder.mkdirs();

This code always returns "DOES NOT EXIST":

File f = new File(Environment.getDataDirectory() + "/testthreepdf");
if(f.exists())
{
    Log.i("testApp", f.toString() + "EXISTS");
}
else        {
    Log.i("testApp", f.toString() + " DOES NOT EXIST");
}

These are the android permissions:

<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>

Anybody know what's wrong with this code?

Answer

samgak picture samgak · Dec 27, 2014

Environment.getDataDirectory() returns the top-level data folder shared by all apps. You can't create folders there. To create folders in your app's data folder, use getFilesDir() instead, like this:

String intStorageDirectory = getFilesDir().toString();
File folder = new File(intStorageDirectory, "testthreepdf");
folder.mkdirs();

You need a Context to call getFilesDir().

For more information about the difference between getDataDirectory() and getFilesDir(), see this StackOverflow question.