You can simplify your function by using the copyTo function:

fun File.copyInputStreamToFile(inputStream: InputStream) {
    this.outputStream().use { fileOut ->
        inputStream.copyTo(fileOut)
    }
}
Answer from yole on Stack Overflow
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › input-stream.html
inputStream | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io/inputStream · JVM · inline fun File.inputStream(): FileInputStream(source) Constructs a new FileInputStream of this file and returns it as a result. 1.0 · inline fun ByteArray.inputStream(): ByteArrayInputStream(source) ...
🌐
Android Developers
developer.android.com › api reference › fileinputstream
FileInputStream | 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 · 中文 – 简体
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-file › input-stream.html
inputStream - Kotlin Programming Language
Try the revamped Kotlin docs design! ... Constructs a new FileInputStream of this file and returns it as a result.
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › writing inputstream to file in kotlin
Writing InputStream to File in Kotlin | Baeldung on Kotlin
April 28, 2026 - The first approach is to use the copyTo(output) extension function on InputStream in Kotlin.
🌐
Medium
medium.com › @sujitpanda › file-read-write-with-kotlin-io-31eff564dfe3
File Read/Write with Kotlin IO. In this post i will be explaining how… | by Sujit Panda | Medium
February 13, 2024 - File Read/Write with Kotlin IO In this post, I will be explaining how to read/write files in Kotlin. I was working on an Android project that was written in Java. I was trying to port one Java file …
🌐
TutorialKart
tutorialkart.com › kotlin › read-contents-of-a-file-in-kotlin
How to Read a File in Kotlin using BufferedReader or InputStream
June 19, 2017 - When you create a reader directly, close it after use. In Kotlin, the common pattern is to wrap the reader in use { }, so the reader is closed automatically even if an exception occurs.
🌐
Compile N Run
compilenrun.com › kotlin tutorial › kotlin io › kotlin input output streams
Kotlin Input Output Streams | Compile N Run
Kotlin leverages Java's IO libraries but adds its own extensions and utilities to make working with streams more concise and safe. The primary input stream classes you'll work with include: InputStream: Base abstract class for all byte input streams ... import java.io.File import java.io.FileInputStream fun main() { val file = File("sample.txt") // Using FileInputStream (byte stream) FileInputStream(file).use { fis -> val bytes = ByteArray(file.length().toInt()) fis.read(bytes) println("File content (as bytes converted to string): ${String(bytes)}") } // More idiomatic Kotlin way using extension functions println("File content (using readText()): ${file.readText()}") // Reading line by line file.forEachLine { line -> println("Line: $line") } }
Find elsewhere
🌐
BezKoder
bezkoder.com › home › how to read file in kotlin
How to read File in Kotlin - BezKoder
February 16, 2020 - Way to read File in Kotlin line-by-line/all lines using InputStream or BufferedReader or File directly.
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 › core › kotlin-stdlib › kotlin.io
kotlin.io | Core API – Kotlin Programming Language
Since Kotlin 1.0 · input · Stream · Link copied to clipboard · JVM · inline fun File.inputStream(): FileInputStream · Constructs a new FileInputStream of this file and returns it as a result.
🌐
GeeksforGeeks
geeksforgeeks.org › read-from-files-using-inputreader-in-kotlin
Read From Files using InputReader in Kotlin - GeeksforGeeks
March 13, 2022 - Basically, kotlin.io provides a nice, clean API for reading from and writing to files. In this article, we are going to discuss how to read from files using inputReader in Kotlin. One way of doing this is by using inputreader.
🌐
Medium
kabi20.medium.com › i-o-streams-in-kotlin-5a4d00107167
I/O Streams in Kotlin | Medium
May 10, 2026 - FileInputStream() opens the pipe or connection to the actual file on the disk so data can flow from the file into your program. If the hello.txt file do not exists then it will lead to crash with FileNotFoundException.
🌐
Medium
medium.com › @devrath.dev595 › handling-input-stream-using-kotlin-dbc404f03967
Handling input stream using kotlin | by Devrath | Medium
February 20, 2022 - Handling input stream using kotlin In earlier days prior to kotlin Handling the input stream used to be a challenge. Whenever we think of reading data from a file stored in a project, That can …
🌐
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
* Constructs a new FileInputStream of this file and returns it as a result. */ @kotlin.internal.InlineOnly · public inline fun File.inputStream(): FileInputStream { return FileInputStream(this) } · /** * Constructs a new FileOutputStream of this file and returns it as a result.
Author   JetBrains
🌐
O'Reilly
oreilly.com › library › view › kotlin-programming-by › 9781788474542 › 9746b052-8766-427d-b298-26eb5d9bf64f.xhtml
Reading files from internal storage - Kotlin Programming By Example [Book]
March 28, 2018 - In order to read a private file, get a FileInputStream by calling openFileInput(). This method takes a single argument—the name of the file to be read. openFileInput() must be called within an instance of Context.
Author   Iyanu Adelekan
Published   2018
Pages   500
Top answer
1 of 2
1

Using "externalCacheDir" instead of "cacheDir" while creating file might solve the problem.

requireContext().externalCacheDir?.let {
            val file = File(
                    it.path,
                    requireContext().contentResolver.getFileName(uri!!)
            )
            file.createNewFile()

        }
2 of 2
1

Sending image to php server using Okhttp: First covert all images to byte array and put it in "backupData" list. Then call "backupOneByOne()" method.

private var client: OkHttpClient = OkHttpClient()

init {
    client.setReadTimeout(5, TimeUnit.MINUTES)
    client.setConnectTimeout(5, TimeUnit.MINUTES)
}
val backupData: MutableList<ByteArray> = mutableListOf()

private suspend fun backupOneByOne(currentPosition: Int, byteArray: ByteArray) {
    val backupResponse = doBackupMultiPartData("merchantKey", byteArray)

    when (backupResponse) {
        is ResponseResult.Success -> {
            Log.d("nm==>>", "Menu Item backup successful !!! AND current item position= $currentPosition")
            if (currentPosition < backupData.size - 1) {
                backupOneByOne(currentPosition + 1, backupData[currentPosition + 1])
            } else {
                Log.d("nm==>>", "Backup of all items is done. Current position= $currentPosition")
            }
        }
        is ResponseResult.Error -> {
            Log.d("nm==>>", "Error while backup of Advance table : \n ${backupResponse.msg.errorMsg}")
        }
        else -> {
        }
    }
}
suspend fun doBackupMultiPartData(apiKey: String, imageData: ByteArray?): ResponseResult<ResponseWrapper<String>> {
    val requestBody = MultipartBuilder().type(MultipartBuilder.FORM)
    //requestBody.addFormDataPart("id",2) put other form data fields
    if (imageData != null) {
        requestBody.addFormDataPart(
                "file", "Logo.png", RequestBody.create(
                MediaType.parse(
                        "image/png"
                ), imageData
        )
        )
    }

    val request = Request.Builder()
            .header("api_key", apiKey) // getting api key from backend
            .url("put url here....")
            .post(requestBody.build())
            .build()
    try {
        val result = apiRequest(request)
        Log.d("nm==>>", "Result: $result")
        return if (result != null) {
            val jsonObject = JSONObject(result)
            if (jsonObject.getBoolean("isSuccessful")) {
                ResponseResult.Success(ResponseWrapper("success", null))
            } else {
                ResponseResult.Error(
                        ResponseWrapper(null, "Back end code error: \n $result")
                )
            }
        } else {
            ResponseResult.Error(
                    ResponseWrapper(
                            null, "Getting NULL as result"
                    )
            )
        }
    } catch (jsonException: JSONException) {
        Log.d("nm==>>", "Restore JSON exception::: \n ${jsonException.localizedMessage}")
        return ResponseResult.Error(
                ResponseWrapper(
                        null,
                        "Restore Json Exception"
                )
        )
    } catch (exception: Throwable) {
        //Log.d("nm==>>", "Network exception::: \n ${exception.localizedMessage}")
        return ResponseResult.NoInternet
    }
}

private suspend fun apiRequest(request: Request): String? = suspendCancellableCoroutine { cancellableContinuation ->
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(request: Request?, e: IOException?) {
            cancellableContinuation.resumeWith(Result.failure(Throwable("API failed.....${e?.localizedMessage}")))
        }

        override fun onResponse(response: Response?) {
            cancellableContinuation.resumeWith(Result.success(response?.body()?.string()))
        }
    })
}
sealed class ResponseResult<out T> {
    object Loading:ResponseResult<Nothing>()
    object Empty:ResponseResult<Nothing>()
    data class Success<T>(val result:T): ResponseResult<T>()
    data class Error<T>(val msg:T): ResponseResult<T>()
    object NoInternet:ResponseResult<Nothing>()
}
data class ResponseWrapper<out T>(val data: T?, val errorMsg: String?)