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() } } }
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.
You can simplify your function by using the copyTo function:
fun File.copyInputStreamToFile(inputStream: InputStream) { this.outputStream().use { fileOut -> inputStream.copyTo(fileOut) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With