Kotlin has a specific extension just for this purpose.

The simplest:

val inputAsString = input.bufferedReader().use { it.readText() }  // defaults to UTF-8

And in this example, you could decide between bufferedReader() or just reader(). The call to the function Closeable.use() will automatically close the input at the end of the lambda's execution.

Further reading:

If you do this type of thing a lot, you could write this as an extension function:

fun InputStream.readTextAndClose(charset: Charset = Charsets.UTF_8): String {
    return this.bufferedReader(charset).use { it.readText() }
}

Which you could then call easily as:

val inputAsString = input.readTextAndClose()  // defaults to UTF-8

On a side note, all Kotlin extension functions that require knowing the charset already default to UTF-8, so if you require a different encoding you need to adjust the code above in calls to include encoding for reader(charset) or bufferedReader(charset).

Warning: You might see examples that are shorter:

val inputAsString = input.reader().readText() 

But these do not close the stream. Make sure you check the API documentation for all of the IO functions you use to be sure which ones close and which do not. Usually, if they include the word use (such as useLines() or use()) they close the stream after. An exception is that File.readText() differs from Reader.readText() in that the former does not leave anything open and the latter does indeed require an explicit close.

See also: Kotlin IO related extension functions

🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › input-stream.html
inputStream | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io/inputStream ... 1.0 · inline fun ByteArray.inputStream(): ByteArrayInputStream(source) Creates an input stream for reading data from this byte array....
Top answer
1 of 4
332

Kotlin has a specific extension just for this purpose.

The simplest:

val inputAsString = input.bufferedReader().use { it.readText() }  // defaults to UTF-8

And in this example, you could decide between bufferedReader() or just reader(). The call to the function Closeable.use() will automatically close the input at the end of the lambda's execution.

Further reading:

If you do this type of thing a lot, you could write this as an extension function:

fun InputStream.readTextAndClose(charset: Charset = Charsets.UTF_8): String {
    return this.bufferedReader(charset).use { it.readText() }
}

Which you could then call easily as:

val inputAsString = input.readTextAndClose()  // defaults to UTF-8

On a side note, all Kotlin extension functions that require knowing the charset already default to UTF-8, so if you require a different encoding you need to adjust the code above in calls to include encoding for reader(charset) or bufferedReader(charset).

Warning: You might see examples that are shorter:

val inputAsString = input.reader().readText() 

But these do not close the stream. Make sure you check the API documentation for all of the IO functions you use to be sure which ones close and which do not. Usually, if they include the word use (such as useLines() or use()) they close the stream after. An exception is that File.readText() differs from Reader.readText() in that the former does not leave anything open and the latter does indeed require an explicit close.

See also: Kotlin IO related extension functions

2 of 4
4

Method 1 | Manually Close Stream

private fun getFileText(uri: Uri):String {
    val inputStream = contentResolver.openInputStream(uri)!!

    val bytes = inputStream.readBytes()        //see below

    val text = String(bytes, StandardCharsets.UTF_8)    //specify charset

    inputStream.close()

    return text
}
  • inputStream.readBytes() requires manually close the stream: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/read-bytes.html

Method 2 | Automatically Close Stream

private fun getFileText(uri: Uri): String {
    return contentResolver.openInputStream(uri)!!.bufferedReader().use {it.readText() }
}
  • You can specify the charset inside bufferedReader(), default is UTF-8: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/buffered-reader.html

  • bufferedReader() is an upgrade version of reader(), it is more versatile: How exactly does bufferedReader() work in Kotlin?

  • use() can automatically close the stream when the block is done: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html

🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › input-stream.html
inputStream - Kotlin Programming Language
July 19, 2022 - ... 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. offset - the start offset of the portion of the array to read.
🌐
Kotlin Discussions
discuss.kotlinlang.org › t › java-byte-and-kotlin-bytearray-question › 1065
Java byte[] and Kotlin ByteArray question - Kotlin Discussions
October 13, 2012 - Any hint or idea will do Java code: public static ByteArrayOutputStream convert(InputStream stream) { final ByteArrayOutputStream out = new ByteArrayOutputStream(8192); byte buffer = new byte[8192]; int length; try { while ((length = ...
🌐
Baeldung
baeldung.com › home › java › java io › java byte array to inputstream
Java Byte Array to InputStream | Baeldung
December 7, 2023 - @Test public void givenUsingPlainJava_whenConvertingByteArrayToInputStream_thenCorrect() throws IOException { byte[] initialArray = { 0, 1, 2 }; InputStream targetStream = new ByteArrayInputStream(initialArray); } Next – let’s use wrap the byte array into the Guava ByteSource – which then allows us to get the stream:
🌐
Android Developers
developer.android.com › api reference › bytearrayinputstream
ByteArrayInputStream | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
GitHub
github.com › JetBrains › kotlin › blob › master › libraries › stdlib › jvm › src › kotlin › io › IOStreams.kt
kotlin/libraries/stdlib/jvm/src/kotlin/io/IOStreams.kt at master · JetBrains/kotlin
* Creates an input stream for reading data from this byte array. */ @kotlin.internal.InlineOnly · public inline fun ByteArray.inputStream(): ByteArrayInputStream = ByteArrayInputStream(this) · /** * Creates an input stream for reading data from the specified portion of this byte array.
Author   JetBrains
Find elsewhere
🌐
GitHub
github.com › Kotlin › kotlinx-io › issues › 291
Construct a ByteArrayInputStream from a ByteString without copying bytes or using UnsafeByteStringOperations · Issue #291 · Kotlin/kotlinx-io
April 5, 2024 - Construct a ByteArrayInputStream from a ByteString without copying bytes or using UnsafeByteStringOperations#291
Author   mgroth0
🌐
HugeDomains
gaumala.com › posts › 2020-01-27-working-with-streams-kotlin.html
Working with byte streams in Kotlin
January 27, 2020 - Great domain names provide SEO, branding, and a memorable experience for your users. Get a premium domain today.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-input-stream › read-bytes.html
readBytes - Kotlin Programming Language
Try the revamped Kotlin docs design! ... Creates a buffered input stream wrapping this stream. fun InputStream.buffered( bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedInputStream ... Creates a buffered reader on this input stream using UTF-8 or the specified charset. fun InputStream.bufferedReader( charset: Charset = Charsets.UTF_8 ): BufferedReader ... Reads this stream completely into a byte array...
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-input-stream
java.io.InputStream - Kotlin Programming Language
January 6, 2022 - Copies this stream to the given output stream, returning the number of bytes copied · fun InputStream.copyTo( out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long · JVM · 1.0 · Reads this stream completely into a byte array. fun InputStream. readBytes( estimatedSize: Int = DEFAULT_BUFFER_SIZE ): ByteArray ·
🌐
Luasoftware
code.luasoftware.com › tutorials › kotlin › inputstream-to-bytearray-and-string
InputStream To Bytearray And String (Kotlin)
April 20, 2018 - kotlin · inputstream · string · val outputStream = ByteArrayOutputStream()inputStream.use { input -> outputStream.use { output -> input.copyTo(output) }}val byteArray = outputStream.toByteArray()val outputString = String(byteArray, Charsets.UTF_8) ❤️ Is this article helpful?
🌐
Programiz
programiz.com › kotlin-programming › examples › convert-inputstream-string
Kotlin Program to Convert InputStream to String
import java.io.* fun main(args: Array<String>) { val stream = ByteArrayInputStream("Hello there!".toByteArray()) val sb = StringBuilder() var line: String? val br = BufferedReader(InputStreamReader(stream)) line = br.readLine() while (line != null) { sb.append(line) line = br.readLine() } br.close() println(sb) } When you run the program the output will be: Hello there!
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › read-bytes.html
readBytes | Core API – Kotlin Programming Language
It has an internal limitation of 2 GB byte array size. 1.0 · the entire content of this file as a byte array. fun InputStream.readBytes(): ByteArray(source) Reads this stream completely into a byte array.
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › inputstream to string in kotlin
InputStream to String in Kotlin | Baeldung on Kotlin
April 19, 2024 - In Kotlin, we can convert a String to an InputStream using the ByteArrayInputStream class. This class takes a ByteArray as its constructor argument.
🌐
GitHub
github.com › JetBrains › kotlin › blob › master › libraries › stdlib › jvm › src › kotlin › io › FileReadWrite.kt
kotlin/libraries/stdlib/jvm/src/kotlin/io/FileReadWrite.kt at master · JetBrains/kotlin
@kotlin.internal.InlineOnly · public inline fun File.printWriter(charset: Charset = Charsets.UTF_8): PrintWriter = PrintWriter(bufferedWriter(charset)) · /** * Gets the entire content of this file as a byte array. * * This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size. * * @return the entire content of this file as a byte array. */ public fun File.readBytes(): ByteArray = inputStream().use { input -> var offset = 0 ·
Author   JetBrains