stringkotlininputstream

How to convert a String to an InputStream in Kotlin?


I have a string:

var myString:String  = "My String"

How can I convert it to an InputStream in Kotlin?


Solution

  • Kotlin has an extension for String to convert directly.

    val inputStream: InputStream = myString.byteInputStream()
    

    The argument on byteInputStream is defaulted to charset: Charset = Charsets.UTF_8.

    You can look at the extension by writing it and then cmd+click on it or in the package kotlin.io file IOStream.kt

    Relying on the Java version is not wrong, but rather using a more kotlin idiomatic way when possible