I\'m trying to get from an Android Uri to a byte array.
I have the following code, but it keeps telling me that the byte array is 61 bytes long, even though the fil
Kotlin way:
@Throws(IOException::class)
private fun readBytes(context: Context, uri: Uri): ByteArray? =
context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
In Kotlin, they added convenient extension functions for InputStream
like buffered
, use
, and readBytes
.
buffered
decorates the input stream as BufferedInputStream
use
handles closing the streamreadBytes
does the main job of reading the stream and writing into a byte arrayError cases:
IOException
can occur during the process (like in Java)openInputStream
can return null
. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.