Created
April 28, 2020 07:44
-
-
Save siifii/b9f822e23cdb4ed805f9f048e9e11770 to your computer and use it in GitHub Desktop.
How to Get File Path from URI working on -- Android Oreo (8.1) or above
This file contains 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
fun Uri.toFilePath(context: Context) : String { | |
val id = DocumentsContract.getDocumentId(this) | |
val inputStream = context.contentResolver.openInputStream(this) | |
val file = File(context.cacheDir.absolutePath + "/" + id) | |
writeFile(inputStream!!, file) | |
return file.absolutePath | |
} | |
fun writeFile(`in`: InputStream, file: File?) { | |
var out: OutputStream? = null | |
try { | |
out = FileOutputStream(file) | |
val buf = ByteArray(1024) | |
var len: Int | |
while (`in`.read(buf).also { len = it } > 0) { | |
out.write(buf, 0, len) | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} finally { | |
try { | |
out?.close() | |
`in`.close() | |
} catch (e: IOException) { | |
e.printStackTrace() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment