https://kotlinlang.org logo
Title
e

elect

09/19/2017, 8:40 AM
if I have to write a
ByteBuffer
to file, what's the best way? Using
InputStream
like here: https://stackoverflow.com/questions/35528409/write-a-large-inputstream-to-file-in-kotlin?
d

diesieben07

09/19/2017, 1:11 PM
Embrace `java.nio`:
fun Path.channel(vararg options: OpenOption): FileChannel = FileChannel.open(this, *options)

fun main(args: Array<String>) {
    val buf: ByteBuffer = TODO()
    val file = Paths.get("output")

    file.channel(StandardOpenOption.CREATE, StandardOpenOption.WRITE).use { channel ->
        while (buf.hasRemaining()) channel.write(buf)
    }
}
e

elect

09/19/2017, 5:49 PM
why
while (buf.hasRemaining())
and not simply
channel.write(buf)
?
can it simply write an arbitrarly amount of bytes? Why?
I'll never get these methods..
d

diesieben07

09/19/2017, 6:03 PM
Yes,
channel.write
may write only a portion of the buffer as per the Javadocs.
If you feed it a large buffer, it will only write as much as it can efficiently write in one go.
e

elect

09/19/2017, 6:05 PM
what does it mean?
for which reason would it efficientely write only a portion?
d

diesieben07

09/19/2017, 6:11 PM
Channel
is a very generic interface. It might be a channel bound to a network socket, which only has a limited buffer. You can't just send out 500MB immediately, you have to wait for the network speed. So as long as the network buffer is full, it cannot write.
e

elect

09/19/2017, 8:28 PM
ah, that makes sense, thanks
hi, just a quick question, this is valid also for reading I guess
val buffer = FileChannel.open(path, StandardOpenOption.READ).use { channel ->
            bufferBig(channel.size().i).also {
                while (channel.read(it) > 0) Unit
            }
        }
read()
returns the number of bytes read
d

diesieben07

09/20/2017, 2:09 PM
Yes, but why
also
here?