[英]Write to SD card Android
我想让我的应用程序用户可以选择保存到手机内部存储器或SD卡中。 如果我根据用户的选择创建File
,则URI(无文件名)类似于:
内部:内容:/com.android.externalstorage.documents/tree/primary%3A
SD:内容:/com.android.externalstorage.documents/tree/760E-F734%3A
但是,如果尝试使用以下代码将文件写入这些目录,则会出现错误java.io.IOException: No such file or directory
:
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;
}
因此,该文件将被写入如下位置:
内容:/com.android.externalstorage.documents/tree/primary%3A/ [我的文件名]
我已经在清单中声明了WRITE_EXTERNAL_STORAGE
权限,因此我想这不是权限问题,而更多是无效路径问题。
如果这些不是有效的文件路径,我该如何写SD卡? 使用Environment.getExternalStorageDirectory()
始终写入设备的内部存储(“ / storage / emulated / 0”)。
请检查您的文件路径。 调用getAbsolutePath()函数并检查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);
}
由于路径在不同的设备中不同,您会收到此错误。
尝试使用Environment.getExternalStorageDirectory()
作为writePath
请记住,在Android 6及更高版本中,您必须在运行时请求权限
File
仅适用于文件系统路径或file://
URI,并且您在此处具有content://
URI。 (此外,要从URI创建文件,您可以将其作为Uri
而不是字符串进行传递。)
根据您要对该文件进行的操作, DocumentFile
可能会为您工作。 它旨在提供类似于File
的界面,但围绕Storage Access Framework构建。 您可以获取以这种方式创建的文件的输入和输出流,并执行一些基本的文件操作。
一件令人痛苦的事情是涉及标准Java库的任何事情都需要File
参数,因为没有正式的方法可以从content://
URI到实际的File
实例,除了可能在下一次更新,或在尚未考虑的一台设备上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.