创建后文件不存在

File doesn't exist after being created

使用 MediaStore 我创建了名为 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 :(");
}

文件已创建,我可以毫无问题地打开它们:

但是,为了检查文件是否真的被创建,根据if语句,即使实际创建了文件,文件也不存在。

这是因为此文件在创建时一般无法访问,还是由于文件不可读的权限问题?

ContentProvider 的主要功能之一是封装数据,这样您就不必处理低级别的事情,例如文件。

我不确定您为什么要测试您创建的行是否存在,因为只要插入调用成功,您就知道它确实存在。 Uri.getPath 函数不是 return 文件路径,而是解码后的 Uri 路径,正如您从屏幕截图中看到的那样 "content://media/external/file/{some number}".

如果您想打开您创建的行的内容(Uri returned),您可以使用 Intent。请参阅相关开发人员文档:Content Providers and Intents filters