Will FileChannel#write always write the whole buffer?

心不动则不痛 提交于 2019-11-29 05:40:09

No, there are no guarantees that write() will exhaust the whole buffer. The documentation does try to establish the expectation that implementations should write all bytes in one go, but it takes care to make no promises:

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[1], may write only some of the bytes or possibly none at all.

FileChannel.write() similarly leaves room for incomplete writes:

Writes a sequence of bytes to this channel from the given buffer.

Bytes are written starting at this channel's current file position unless the channel is in append mode, in which case the position is first advanced to the end of the file. The file is grown, if necessary, to accommodate the written bytes, and then the file position is updated with the number of bytes actually written. Otherwise this method behaves exactly as specified by the WritableByteChannel interface.

So, while the text implies the full write to be the general case and incomplete writes to be the exception, it leaves the door open for alternative/future implementations that may not (be able to) adhere to this general case.

As you point out, this is a difference in approach from read(). I imagine this is because, at the time of consolidating the documentation, all known and intended implementations adhered to this general case of performing complete writes.


[1] This is probably a reference to non-blocking channels.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!