Android相机拍照后FileNotFoundException报错的排查与修复
问题分析与修复
你遇到的FileNotFoundException核心原因是目标文件的父目录不存在,相机应用无法自动创建缺失的目录,导致照片无法写入。此外还有几个细节需要完善:
1. 先创建目标目录
在创建文件前,必须确保images目录存在,否则相机无法写入文件:
val activity = requireActivity() // 先获取images目录对象 val imagesDir = File(activity.filesDir, "images") // 递归创建目录(如果不存在) if (!imagesDir.exists()) { imagesDir.mkdirs() } // 再创建文件 val file = File(imagesDir, "go_capture.png")
2. 仅在拍照成功后导航
TakePicture()返回的saved布尔值是关键判断依据——只有它为true时,照片才成功保存到指定Uri。不要忽略这个判断,否则会在拍照失败时仍尝试访问不存在的文件:
val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { saved -> Log.d(MainFragment::class.simpleName, "拍照结果: $saved") if (saved) { val action = MainFragmentDirections.actionImage(imageUri.toString()) view.findNavController().navigate(action) } else { // 可选:提示用户拍照失败 } }
3. 验证FileProvider配置是否正确
检查AndroidManifest.xml中的FileProvider配置,确保authorities和代码中一致,且路径映射正确:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.images.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
然后在res/xml/file_paths.xml中配置对应路径:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 对应filesDir下的images目录 --> <files-path name="images" path="images/" /> </paths>
4. 可选:使用唯一文件名避免覆盖
如果多次拍照,相同文件名会覆盖之前的照片,建议用时间戳生成唯一文件名:
val fileName = "capture_${System.currentTimeMillis()}.png" val file = File(imagesDir, fileName)
内容的提问来源于stack exchange,提问作者Code-Apprentice
相关产品推荐
相关产品推荐

