File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")
File file = new File(writePath, fileName);
try {
file.createNewFile();
} catch (IOException e) {
Log.e("saveSurvey", "Failed to create file!" + e.getMessage());
return false;
So the file would be written somewhere like this:
content:/com.android.externalstorage.documents/tree/primary%3A/[my file name]
I have declared the WRITE_EXTERNAL_STORAGE
permission in the manifest, so I guess it is not a permissions issue but more of an invalid path issue.
If these are not valid file paths, how would I go about writing to the SD card? Using Environment.getExternalStorageDirectory()
always writes to the internal storage of my device ('/storage/emulated/0').
–
–
File
works only with filesystem paths, or with file://
URIs, and you have a content://
URI here. (In addition, to create a file from a URI you would pass that as a Uri
, not as a string.)
Depending on what you are trying to do with the file, DocumentFile
may work for you. It is designed to provide an interface similar to File
but built around the Storage Access Framework. You can obtain input and output streams for the file created that way and do some basic file operations.
The one thing that is a pain is anything involving standard Java libraries which expect a File
argument, as there is no official way to get from a content://
URI to an actual File
instance—apart from hacks which may cease to work after the next update, or on the one device that has not been considered.
You getting this error because the path is different in different devices.
Try to use Environment.getExternalStorageDirectory()
as writePath
Keep in mind in android 6 and above you must request permission at runtime
–
Call a getAbsolutePath() function And checked writePath
File writePath = new File("content:/com.android.externalstorage.documents/tree/primary%3A")
if(writePath.exists() && writePath.isDirectory()) {
//File extensions can be declared
File file = new File(writePath.getAbsolutePath(), fileName+ extensions);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.