Using MediaStore
I've created random test files called po.txt
:
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "po"); //file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain"); //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS ); //end "/" is not mandatory
Uri uri = getContext().getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); //important!
OutputStream outputStream = getContext().getContentResolver().openOutputStream(uri);
outputStream.write("This is menu category data.".getBytes());
outputStream.close();
File f = new File(uri.getPath());
if(f.exists()) {
Log.e("i","never enter this code :(");
} else {
Log.e("i","always enter this code :(");
}
The files are created and I can open them without issues:
However, In order to check if the files are actually created, according to the if statement, the file do not exist even tough the files are actually created.
Is this due to this files are not generell accessable when created, or due to right issues that the files are not readable?
CodePudding user response:
One of the primary features of a ContentProvider is to encapsulate data so you don't have to deal with low level things, like Files.
I'm not sure why you are testing the existence of a row you created, since you know it does exist as long as the insert call succeeded. The Uri.getPath
function does not return the file path, but rather the decoded Uri path, which as you can see from your screenshot is something like "content://media/external/file/{some number}"
.
If you want to open the content of the row you created (the Uri returned) you can use an Intent. See relevant developer documentation: Content Providers and Intents filters