How To Clone InputStream (Kotlin)

April 20, 2018
Copy InputStream as ByteArrayInputStream

One of the reason to clone InputStream is that you might want to read the InputStream multiple times, and not all InputStream support reset.

val inputStream = ...

val byteOutputStream = ByteArrayOutputStream()
inputStream.use { input ->
    byteOutputStream.use { output ->
        input.copyTo(output)
    }
}

val byteInputStream = ByteArrayInputStream(byteOutputStream.toByteArray())
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.