Android - getting from a Uri to an InputStream to a byte array?

前端 未结 7 2022
慢半拍i
慢半拍i 2020-11-30 03:44

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

相关标签:
7条回答
  • 2020-11-30 04:34

    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 stream
    • readBytes does the main job of reading the stream and writing into a byte array

    Error 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.
    0 讨论(0)
提交回复
热议问题