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 OverflowBaeldung
baeldung.com › home › kotlin › kotlin io › writing inputstream to file in kotlin
Writing InputStream to File in Kotlin | Baeldung on Kotlin
April 28, 2026 - So we’re better off avoiding this temptation and let’s get familiar with better ways. The first approach is to use the copyTo(output) extension function on InputStream in Kotlin.
Top answer 1 of 5
109
You can simplify your function by using the copyTo function:
fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}
2 of 5
17
My proposition is:
fun InputStream.toFile(path: String) {
File(path).outputStream().use { this.copyTo(it) }
}
without closing current stream
InputStream.toFile("/path/filename")
also, do not forget to handle exceptions, for example if write permission is denied :)
Luasoftware
code.luasoftware.com › tutorials › kotlin › write-inputstream-to-file
Write InputStream To File - Lua Software Code
val outputStream = FileOutputStream(outputFile)// the following should work as well // val outputStream = outputFile.outputStream()inputStream.use { input -> outputStream.use { output -> input.copyTo(output) }}
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 · 中文 – 简体
YouTube
youtube.com › watch
InputStreams & OutputStreams In Kotlin - IO Essentials - YouTube
In this video you'll learn about input and output streams in Kotlin and how we can use these to read data from and write data to files. ⭐ Courses with real-l...
Published January 22, 2025
Kotlin
kotlinlang.org › docs › tutorials › kotlin-for-py › file-io.html
File I/O - Kotlin Programming Language
val stream = File("data.txt").inputStream() val bytes = ByteArray(16) stream.read(bytes) stream.close() println(bytes) It's important to close a stream when you're done with it; otherwise, your program will leak a file handle. See the next section for how do do this nicely. If you've got one string that you want to write to a file, overwriting the existing contents if the file already exists, do this (again, UTF-8 is the default encoding):
Top answer 1 of 10
122
Here it is, input is your inputStream. Then use same File (name) and FileInputStream to read the data in future.
try {
File file = new File(getCacheDir(), "cacheFileAppeal.srl");
try (OutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
}
} finally {
input.close();
}
2 of 10
37
Simple Function
Try this simple function to neatly wrap it up in:
// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
OutputStream out = null;
try {
out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Ensure that the InputStreams are closed even if there's an exception.
try {
if ( out != null ) {
out.close();
}
// If you want to close the "in" InputStream yourself then remove this
// from here but ensure that you close it yourself eventually.
in.close();
}
catch ( IOException e ) {
e.printStackTrace();
}
}
}
Thanks to Jordan LaPrise and his answer.
Android Developers
developer.android.com › api reference › inputstream
InputStream | 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.-input-stream › copy-to.html
copyTo - Kotlin Programming Language
June 27, 2022 - kotlin-stdlib / kotlin.io / java.io.InputStream / copyTo · JVM · 1.0 · fun InputStream.copyTo( out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE ): Long (source) Copies this stream to the given output stream, returning the number of bytes copied ·
Android Developers
developer.android.com › api reference › fileoutputstream
FileOutputStream | 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
gist.github.com › naddeoa › 4172e84aca533319a1cc5663d2fab39e
Copy input stream in Kotlin with progress · GitHub
To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ... fun InputStream.copyTo(out: OutputStream, streamSize: Long): Flow<Int> { return flow { var bytesCopied: Long = 0 val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var bytes = read(buffer) while (bytes >= 0) { out.write(buffer, 0, bytes) bytesCopied += bytes // Emit stream progress in percentage emit((bytesCopied * 100 / streamSize).toInt()) bytes = read(buffer) } }.flowOn(Dispatchers.IO).distinctUntilChanged() }
GeeksforGeeks
geeksforgeeks.org › read-from-files-using-inputreader-in-kotlin
Read From Files using InputReader in Kotlin - GeeksforGeeks
March 13, 2022 - 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. We will see how to do that in this article. There are a lot of ways to go about reading from a file, but it is very important to understand the motivation behind them so as to be able to use the correct one for our purpose. First, we will try to get the Input Stream of the file and use the reader to read the contents: ... import java. io. File import java . io. InputStream fun main (args: Array<String>) { val inputStream: InputStream = File ("gfg.txt").inputStream() val inputString = inputStream.reader().use {it.readText()} println (inputString) }
Luasoftware
code.luasoftware.com › tutorials › kotlin › copy-inputstream-to-outputstream
Copy InputStream To OutputStream (Kotlin) - Lua Software Code
October 25, 2019 - kotlin · inputstream · outputstream · inputStream.use { input -> outputStream.use { output -> input.copyTo(output) }} ❤️ Is this article helpful? Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free. Do send some 💖 to @d_luaz or share this article.
Stack Overflow
stackoverflow.com › questions › 66534120 › how-can-we-save-a-file-of-any-type-from-an-inputstream-using-kotlin-for-android
How can we save a file of any type from an InputStream using Kotlin for Android? - Stack Overflow
March 11, 2021 - Log.d("RECEIVE", "Sending File: ... Type in order to compress and save to a file. No. If it knows a name it can just write the received bytes to a file output stream....
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-file › output-stream.html
outputStream - Kotlin Programming Language
Try the revamped Kotlin docs design! ... Constructs a new FileOutputStream of this file and returns it as a result.