Skip to content

Instantly share code, notes, and snippets.

@root-ansh
Created September 7, 2025 10:36
Show Gist options
  • Select an option

  • Save root-ansh/f0b5131271e5661caf26f201bb3eee19 to your computer and use it in GitHub Desktop.

Select an option

Save root-ansh/f0b5131271e5661caf26f201bb3eee19 to your computer and use it in GitHub Desktop.
// converts any uri(content/file) to a local temp file first in cache directory for easy read/write
suspend fun Uri.toLocalFile(context: Context,localFileLocation:File = context.cacheDir): File? {
val uri = this
return withContext(Dispatchers.IO) {
try {
val fileInfo = FileInfo.fromSAFUri(context,uri)
val fileName = fileInfo?.nameWithExtension?: "${System.currentTimeMillis()}.bin"
val tempFile = File(localFileLocation, fileName)
context.contentResolver.openInputStream(uri)?.use { inputStream ->
FileOutputStream(tempFile).use { outputStream ->
val buffer = ByteArray(8 * 1024)
var bytesRead: Int
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
}
}
tempFile
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment