How to convert a String to an InputStream in Kotlin? How to convert a String to an InputStream in Kotlin? arrays arrays

How to convert a String to an InputStream in Kotlin?


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


val myString = "text"val targetStream: InputStream = ByteArrayInputStream(initialString.toByteArray())

Pst.If you copy some java code, for example:

String myString = "text";InputStream targetStream = new ByteArrayInputStream(myString.getBytes());

Android Studio will popup "Clipboard content seems to be Java code. Do you want to convert it to Kotlin?