Reputation: 5411
I have following code to write by file channel
fc.write(bytebuffer, position);
In several tutorials i referred this is ok and it does the job fine. But in the javadoc https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#write-java.nio.ByteBuffer-long- this method returns no of bytes written. Therefore my question is, is it possible in some case this will write only part of bytebuffer ? Do i need to wrap this inside a loop ? Is this code has bug waiting to happen ?
Upvotes: 1
Views: 57
Reputation: 1279
The method FileChannel.write(...)
implements the method WritableByteChannel.write(...)
. This interface can be used for many kinds of channels. The WritableByteChannel.write(...)
documentation tells:
Unless otherwise specified, a write operation will return only after writing all of the r requested bytes. Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.
But in your case with a FileChannel
it will always write and returns the remaining element in your ByteBuffer
.
Upvotes: 1