我使用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 :(");
}

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

galleryview openedfile

但是,为了判断文件是否确实创建了,根据if语句,即使文件是实际创建的,文件也不存在.

这是因为文件在创建时不能被generell访问,还是因为文件不可读?

推荐答案

ContentProvider的主要功能之一是封装数据,这样就不必处理文件等低级事务.

我不确定为什么要测试您创建的行的存在性,因为您知道只要insert调用成功,它就存在.Uri.getPath函数不返回文件路径,而是返回已解码的Uri路径,从屏幕截图中可以看到,这类似于"content://media/external/file/{some number}".

如果要打开所创建行的内容(返回的Uri),可以使用Intent.参见相关开发者文档:Content ProvidersIntents filters

Android相关问答推荐

Android深度链接配置中的URL片段匹配'

如何在Reaction Native中显示Google Map iFrame?

从单元测试访问RES/RAW文件

从安卓S原生库的资源中读取json文件

Jetpack Compose中尺寸不断增加的动画

当按下通知时,将Android应用程序置于前台

插入视图模型时,dagger 未命中绑定错误

Jetpack Compose-如何在进入新产品线之前删除单词?

更改选定的切换轨道 colored颜色

为什么 Android Compose 将片段作为参数传递给 Composables 函数?

是否可以在 compose 中使用三次贝塞尔曲线进行动画?

如何在 Jetpack Compose 中对齐按钮底部中心?

从 HiltViewModel @Injection 访问 Application()

如何在 React Native 下载文件之前打开文件管理器并 Select 一个目录

如果 auth 失败,如何显示 toast jetpack compose firebase if else @Composable 调用只能在 @Composable 函数的上下文中发生

调用时 listFiles() nullpointerexception

我的 react native 项目的发布签名 apk 没有在设备中打开,而且它创建的尺寸非常小

如何在 Jetpack Compose 中更改 ModalNavigationDrawer 的抽屉容器 colored颜色 ?

将生成的 AAR 与 Composables 一起使用时未解决的参考

无法将片段中的 recyclerview 与适配器连接