问题描述
我将文件路径传递给 MediaRecorder 以创建视频文件。
File(filePath).exists()
返回假,
但 MediaRecorder 因 IOException 而失败,
java.io.FileNotFoundException:/storage/emulated/0/DCIM/XXX/XXX0001.mp4:打开失败:EEXIST(文件存在)
我尝试通过 getContentResolver().insert()
创建 Uri,但它也给出了 UNIQUE 约束失败:files._data (code 2067 sqlITE_CONSTRAINT_UNIQUE[2067])
问题不在于我从未测试过我的应用程序的新手机。如果我从文件管理器中删除视频,问题就会开始。
解决方法
创建一个临时文件并复制临时文件中的全部内容。
/**
* Create a temp file with the specified format.
* Usage: Image from gallery,Copy file to app directory before upload
*/
@SuppressLint("SimpleDateFormat")
suspend fun createTempFile(fileType: BaseMediaFragment.FileType,extension: String): File? =
withContext(Dispatchers.IO) {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? =
getApplication<Application>().applicationContext?.getExternalFilesDir(fileType.tempFileDirectory)
if (!storageDir?.exists().isTrue())
storageDir?.mkdirs()
return@withContext File.createTempFile(
"${fileType.tempFilePrefix}_${timeStamp}_",/* prefix */
extension,/* suffix */
storageDir /* directory */
)
}
/**
* Copy the specified input stream to the output file.
*/
private suspend fun copyStreamToFile(inputStream: InputStream,outputFile: File) {
withContext(Dispatchers.IO) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024) // buffer size
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer,byteCount)
}
output.flush()
}
}
}
```