Hong
Hong

Reputation: 18501

Why is the parent path of a selected file not usable?

The following code is used to launch a file manager to allow the user to select a file:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, REQUEST_CODE_CUSTOM_FOLDER);

If the user selects file foo.txt in folder Download, the returned file's path is

/document/2071-13DB:Download/foo.txt

There is no problem in reading that file. When the app tries to write a text file (foo_new.txt) to folder "/document/2071-13DB:Download", it gets the following exception:

Error:Directory '/document/2071-13DB:Download' could not be created.

Could anyone shed some light on this? I am trying to allow the user to select a folder for the app to save files.

Upvotes: 0

Views: 371

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006944

The following code is used to launch a file manager to allow the user to select a file

No, it is not. It is used to get a piece of content, from any activity that support that particular Intent structure.

If the user selects file foo.txt in folder Download, the returned file's path is

You are not getting a file. You are getting a Uri to a piece of content. In particular, I strongly suspect that this Uri has a content scheme. In that case, the path is meaningless to you.

When the app tries to write a text file (foo_new.txt) to folder "/document/2071-13DB:Download", it gets the following exception

That is not a folder. From your standpoint, that is a random series of characters.

For example, the URL of this Web page is https://stackoverflow.com/questions/39337012/why-is-the-parent-path-of-a-selected-file-not-usable. You can use an HTTP client to read the contents of that page. However, if you try using Java's File object to write a new file to /questions/39337012/ on your computer, you will find that this will not work, because you do not have a /questions/39337012/ folder on your computer. Here, the URL points to content that is not on your computer's filesystem.

Similarly, you cannot perform string manipulations of a portion of a Uri and come up with another Uri that you can use. A Uri does not have to point to a file on the filesystem.

I am trying to allow the user to select a folder for the app to save files.

Use a directory-chooser library, then.

Or, on Android 5.0+ devices, use ACTION_OPEN_DOCUMENT_TREE, which is part of the Storage Access Framework. From there, use DocumentFile to create new folders, create new content in those folders, etc., all using Uri values without trying to decipher the pieces of the Uri values (e.g., getPath()).

Upvotes: 1

Related Questions