Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Anisuzzaman Babla Avatar asked Oct 02 '20 13:10

Anisuzzaman Babla


People also ask

What is kotlin InputStream?

Creates an input stream for reading data from this byte array. Creates an input stream for reading data from the specified portion of this byte array.

How do you convert Bytearray to string in Kotlin?

To convert a byte array to string in Kotlin, use String() constructor. String() constructor can take a Byte Array as argument and return a new string formed with the bytes in the given array.


1 Answers

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

like image 102
cutiko Avatar answered Oct 18 '22 07:10

cutiko