-1

I have a problem with creating files in Android. I have followed this tutorial, and wrote this method:

public File getStorageDir(String name) {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
        File file = new File(path, name);

        System.out.println(path);
        if (!file.mkdirs()) {
            System.out.println("Directory not created");
        }

        return file;
    }

Path variable prints /storage/emulated/0/Documents, however if goes off and no such directory is created. I have added

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

permissions to manifest file. I have tried using file.getParentFile().mkdirs() but got same result. What am I doing wrong?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
somik07
  • 39
  • 9

2 Answers2

0

You use below code to create folder.

File folder = new File(Environment.getExternalStorageDirectory() +
                File.separator + "folderName");

        if (!folder.exists()) {
            success = folder.mkdirs();
        }
amit semwal
  • 345
  • 3
  • 16
-1

So turns out it was being created the whole time, just not visible in file explorer. I have fixed it with answer from this post. Final code looks like this:

public File getStorageDir(Context context, String name) {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath();
        File file = new File(path, name);

        file.getParentFile().mkdirs();

        MediaScannerConnection.scanFile(context, new String[] {path}, null, null);

        return file;
    }

Thanks everyone for answers, hope this helps someone who faces same problem.

somik07
  • 39
  • 9
  • Well this function creates file in specified folder. I would say that it is something. And it solves problem with MTP protocol, as explained in linked post. No need to be so grumpy. – somik07 Mar 15 '18 at 16:21
  • It does not create a file. Sorry. – greenapps Mar 15 '18 at 20:25