Search code examples
javaandroidandroid-intentandroid-external-storage

How to create directories and files inside a directory obtained by Intent.ACTION_OPEN_DOCUMENT_TREE?


I am using following code to request user to pick a directory for storing app data.

    void doStuff() {
        File f = new File(Prefs.externalURI.getPath(), "cache");
        if (!f.exists()) {
            f.mkdirs();
        }
    }

In onCreate

if (Prefs.externalURI == null) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, DIR_REQ_CODE);
} else {
    doStuff();
}

Here's onActivityResult

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DIR_REQ_CODE && resultCode == RESULT_OK && data != null) {
            Prefs.externalURI = data.getData();
            if (Prefs.externalURI != null) {
                getContentResolver().takePersistableUriPermission(Prefs.externalURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(getFilesDir(), PREFS_PATH));
                    fileOutputStream.write(Prefs.externalURI.toString().getBytes());
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                doStuff();
            }
        }
    }

However, the cache directory is not created. No meaningful errors thrown.

Am I doing something wrong here?

I also tried manually adding write external storage permission. And no error is thrown related to this.


Solution

  • Thanks @CommonsWare.

    Created directory and files using following code

    DocumentFile dir = Objects.requireNonNull(DocumentFile.fromTreeUri(getApplicationContext(), Prefs.externalURI)).createDirectory("cache");
    assert dir != null;
    DocumentFile file = dir.createFile("txt", "my-file.txt");
    

    Looking for ways to write to this file and if there is a way to create a file and nested directories with multiple nesting levels.