Skip to content

Instantly share code, notes, and snippets.

@siifii
Created April 28, 2020 07:44
Show Gist options
  • Save siifii/b9f822e23cdb4ed805f9f048e9e11770 to your computer and use it in GitHub Desktop.
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
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