Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7490

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?

Upvotes: 27

Views: 20997

Answers (2)

cutiko
cutiko

Reputation: 10527

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

Upvotes: 59

Nirel
Nirel

Reputation: 1925

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?

Upvotes: 0

Related Questions