Android使用FileProvider调用相机拍照存储后文件名被拼接额外数字
问题原因
你调用的File.createTempFile()API本身的设计逻辑就是会自动在传入的文件名前缀、后缀之间拼接一段随机唯一数字串,目的是避免临时文件重名冲突,你看到的额外数字串就是这段自动生成的内容。
解决方案
不需要使用临时文件创建API,直接手动构造指定名称的File对象即可,推荐方案如下:
@SuppressLint("SimpleDateFormat") private File getImageFile() throws IOException { // 可在时间戳末尾增加毫秒位,进一步降低重名概率 String timeTicks = new SimpleDateFormat("ddMMMyyyy_hhmmss_SSS").format(new Date()); String imageName = "img-" + timeTicks + ".jpg"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); // 确保存储目录存在 if (!storageDir.exists()) { storageDir.mkdirs(); } File imageFile = new File(storageDir, imageName); imageName = imageFile.getName(); currentImagePath = imageFile.getAbsolutePath(); return imageFile; }
如果你的业务逻辑必须保留createTempFile的调用逻辑,也可以在创建完临时文件后执行重命名操作:
// 原有createTempFile调用完成后添加以下代码 File targetFile = new File(storageDir, imageName + ".jpg"); if (imageFile.renameTo(targetFile)) { imageFile = targetFile; // 更新文件名和路径变量 imageName = imageFile.getName(); currentImagePath = imageFile.getAbsolutePath(); }
补充说明
- 你当前使用的
getExternalFilesDir()拿到的是应用专属存储目录,不属于设备公共根目录,如果需要将文件存储到公共根目录,需要适配Android 10及以上的分区存储规则,使用MediaStoreAPI完成写入,同时申请对应的存储权限。 - SimpleDateFormat是非线程安全的,不要将其声明为全局静态变量,当前局部使用的写法符合规范。
内容的提问来源于stack exchange,提问作者Muhammad Asad.
相关产品推荐
相关产品推荐

