17

Is there any way/ is it allowed to create folders in Internal Memory in Android. Example :

- data
-- com.test.app (application's main package)
---databases (database files)
---files (private files for application)
---shared_prefs (shared preferences)

---users (folder which I want to create)

Can I create users folder in Internal Memory for example?

Android-Droid
  • 14,365
  • 41
  • 114
  • 185

7 Answers7

43

I used this to create folder/file in internal memory :

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
Android-Droid
  • 14,365
  • 41
  • 114
  • 185
  • Seems a helpful answer from the upvotes.. Can you please mention the code for reading the contents of same file, line by line..Since now the file is inside the "mydir" directory, how to do the reading of it..And what if there are further folders in the directory? The "path" is what i am concerned about. – Gautam Mandsorwale Oct 09 '12 at 13:23
  • 1
    @Gautam M. Check if this tutorial works for you. Thanks. http://www.mysamplecode.com/2012/06/android-internal-external-storage.html – JibW Oct 31 '12 at 09:40
  • 1
    FYI on my Huawei the private files/folders are stored here: /data/user/0/your.app.name. It is also the only folder that the app itself can access. Some phones are not so restrictive and let you access even the root directory. – Marcell Jul 23 '19 at 17:31
22

YOU SHOULD NOT USE THIS IF YOU WANT YOUR FILES TO BE ACCESSED BY USER EASILY

File newdir= context.getDir("DirName", Context.MODE_PRIVATE);  //Don't do
if (!newdir.exists())
    newdir.mkdirs();

INSTEAD, do this:

To create directory on phone primary storage memory (generally internal memory) you should use following code. Please note that ExternalStorage in Environment.getExternalStorageDirectory() does not necessarily refers to sdcard, it returns phone primary storage memory

File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");

if (!mediaStorageDir.exists()) {
    if (!mediaStorageDir.mkdirs()) {
        Log.d("App", "failed to create directory");
    }
}

Directory created using this code will be visible to phone user easily. The other method (mentioned first) creates directory in location (/data/data/package.name/app_MyDirName), hence normal phone user will not be able to access it easily and so you should not use it to store video/photo etc.

You will need permissions, in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
prodev
  • 575
  • 5
  • 15
  • yes, you are right, getExternalStorageDirectory() refers to the phone's primary storage,how do you create a folder in sd card then?? – karthik vishnu kumar Dec 19 '16 at 13:29
  • 1
    This code is not creating a separate folder like whatsapp.. – Satheesh Guduri Sep 01 '20 at 09:37
  • 1
    @prodev getExternalStorageDirectory() is not creating folder under internal storage just creating in sdcard for real device... We tested your answer and not worked... – saulyasar Nov 26 '20 at 06:29
  • For me it's working fine in Emulator, But when I tried to run same application using usb cable in physical, It shows _Error:: failed to create directory_. I have also allowed storage access.@prodev – Suthar Aug 04 '21 at 22:52
4

Android change his security about Storage, For more details check the video Storage access with Android 10

Also you can try this in android 10

File mydir = new File(getApplicationContext().getExternalFilesDir("Directory Name").getAbsolutePath());
    if (!mydir.exists())
    {
        mydir.mkdirs();
        Toast.makeText(getApplicationContext(),"Directory Created",Toast.LENGTH_LONG).show();
    }

The path of your directory will be in your app data.

4

context.getDir("mydir", ...); This creates your.package/app_mydir/

 /** Retrieve or creates <b>path</b>structure inside in your /data/data/you.app.package/
 * @param path "dir1/dir2/dir3"
 * @return
 */
private File getChildrenFolder(String path) {
            File dir = context.getFilesDir();
    List<String> dirs = new ArrayList<String>(Arrays.<String>asList(path.split("/")));
    for(int i = 0; i < dirs.size(); ++i) {
        dir = new File(dir, dirs.get(i)); //Getting a file within the dir.
        if(!dir.exists()) {
            dir.mkdir();
        }
    }
    return dir;
}
StepanM
  • 4,222
  • 1
  • 21
  • 25
0
  private File createFile(String fName)  {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/" + fName+".wav";
            File newFile = new File(filePath);
            println(":File path = "+newFile+"\n "+filePath);
            if (!newFile.exists()) {
                try {
                    newFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    toastMsg("Unable to Create New File !");
                }
            } else {
                toastMsg("File Already Exists");

            }

            return newFile;

        }

//Request Multiple Permissions

private void reqMulPerm(){
        String permissions[]={
                Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };

        if(permissions.length!=0){
            ActivityCompat.requestPermissions(this,permissions,1);
        }
    }
Suresh B B
  • 1,387
  • 11
  • 13
0
File f = new File(Environment.getExternalStorageDirectory(), "FolderName");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
               Files.createDirectory(Paths.get(f.getAbsolutePath()));
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }
        } else {
            f.mkdir();
            f.mkdirs();
            Toast.makeText(getApplicationContext(), f.getPath(), Toast.LENGTH_LONG).show();
        }
Meet Bhavsar
  • 442
  • 6
  • 12
0
//gets path of the directory("imRec") in Android's data folder
File file=new File(getApplicationContext().getExternalFilesDir("imRec").getAbsolutePath());

if (!file.exists()) {  //if directory by that name doesn't exist
    if (!file.mkdirs()) { //we create the directory
          //if still directory doesn't get created ERROR mssg gets displayed
          //which in most cases won't happen
          Toast.makeText(CameraActivity.this, "ERROR", Toast.LENGTH_SHORT).show();          
    }
}
ursTruly
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 19 '21 at 19:51