Search code examples
androidandroid-file

Create a file folder for app


The below code doesn't create a folder in my device.

    String intStorageDirectory = context.getFilesDir().toString();
    File folder = new File(intStorageDirectory, "test");
    folder.createNewFile();;

I need a folder created for my app to store media, when user installs it. That folder should be visible on file explorer. How can i do it?


Solution

  • With the current snippet you created a file, you can also create folder by creating file but your current directory is the base folder, getFilesDir() points internal storage for your app which not visible nor accessible unless explicitly declared. You can create a folder and file by creating with new File().createNewFile() or create only folder using mkdirs() but you won't be able to display it using a file explorer app and that folder and files inside it will be deleted when/if user uninstalls your app.

    To save files externally(This doesn't mean saving to SD Card) you can create directory and file with

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), folderName);
    if (!mediaStorageDir.exists()) {
        mediaStorageDir.mkdirs()
    }
    File mediaFile = new File(mediaStorageDir.getAbsolutePath() + File.separator + fileName);
    

    And you need some kind of OutputStream to write data to that file.

    Make sure that you ask <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> inside your AndroidManifest.xml file and ask write permission on runtime if your android:targetSdkVersion="23" or above