Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a large Inputstream to File in Kotlin

Tags:

kotlin

I have a large stream of text coming back from REST web service and I would like to write it directly to file. What is the simplest way of doing this?

I have written the following function extension that WORKS. But I can't help thinking that there is a cleaner way of doing this.

Note: I was hoping to use try with resources to auto close the stream and file

fun File.copyInputStreamToFile(inputStream: InputStream) {     val buffer = ByteArray(1024)      inputStream.use { input ->         this.outputStream().use { fileOut ->              while (true) {                 val length = input.read(buffer)                 if (length <= 0)                     break                 fileOut.write(buffer, 0, length)             }             fileOut.flush()         }     } } 
like image 647
Jeff Campbell Avatar asked Feb 20 '16 20:02

Jeff Campbell


People also ask

What is kotlin InputStream?

An InputStream you can create on a ParcelFileDescriptor, which will take care of calling android. PushbackInputStream. A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" bytes, by storing pushed-back bytes in an internal buffer.


1 Answers

You can simplify your function by using the copyTo function:

fun File.copyInputStreamToFile(inputStream: InputStream) {     this.outputStream().use { fileOut ->         inputStream.copyTo(fileOut)     } } 
like image 103
yole Avatar answered Oct 31 '22 11:10

yole