https://kotlinlang.org logo
Title
j

Jose A.

09/14/2021, 11:59 AM
I need to save the request body to a file. Something like this:
post {
   val targetChannel = FileOutputStream(Files.createTempFile("job-", ".json").toFile()).channel
   val originChannel = newChannel(call.receiveStream())

   originChannel.use {
       targetChannel.use {
            targetChannel.transferFrom(originChannel, 0L, 100000)
       }
    }
...
FileOutputStream, etc. are blocking calls. Is there a nonblocking API to write to files so I can use
receiveChannel()
?
a

Aleksei Tirman [JB]

09/14/2021, 12:52 PM
You can use a
ByteWriteChannel
instance created from a file to copy bytes from input to output channel:
post {
    val tmpFile = Files.createTempFile("job-", ".json").toFile()
    call.receiveChannel().copyTo(tmpFile.writeChannel())
}
👍 2
j

Jose A.

09/14/2021, 1:50 PM
Very nice!
No need to close writeChannel or receiveChannel?
a

Aleksei Tirman [JB]

09/14/2021, 1:53 PM
Better use
call.receiveChannel().copyAndClose(tmpFile.writeChannel())
instead
👍 1