Created
September 7, 2025 10:36
-
-
Save root-ansh/f0b5131271e5661caf26f201bb3eee19 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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