问题描述
例如,我有一个文件,其内容为:
For example I have a file whose content is:
abcdefg
然后我使用以下代码读取'defg'.
then i use the following code to read 'defg'.
ByteBuffer bb = ByteBuffer.allocate(4);
int read = channel.read(bb, 3);
assert(read == 4);
因为文件中有足够的数据,我可以这样认为吗?我可以假设仅当文件中没有足够的字节数时,该方法才返回小于给定缓冲区限制的数字吗?
Because there's adequate data in the file so can I suppose so? Can I assume that the method returns a number less than limit of the given buffer only when there aren't enough bytes in the file?
推荐答案
Javadoc说:
并给出一些示例,以及
这不足以让您做出这样的假设.
This is NOT sufficient to allow you to make that assumption.
实际上,从文件读取时,您很可能总是获得完整的缓冲区,以文件结尾方案为模.考虑到进行系统调用的开销,从OS实施的角度来看这很有意义.
In practice, you are likely to always get a full buffer when reading from a file, modulo the end of file scenario. And that makes sense from an OS implementation perspective, given the overheads of making a system call.
但是,我也可以想象返回半空缓冲区的情况可能是有意义的.例如,通过慢速网络链接从本地安装的远程文件系统中读取数据时,返回部分填充的缓冲区,以便应用程序可以开始处理数据,这具有一些优势.在这种情况下,某些将来的OS可能会实现read
系统调用.如果假设您总是会得到一个完整的缓冲区,那么当您的应用程序在(假设的)新平台上运行时,您可能会感到惊讶.
But, I can also imagine situations where returning a half empty buffer might make sense. For example, when reading from a locally-mounted remote file system over a slow network link, there is some advantage in returning a partially filled buffer so that the application can start processing the data. Some future OS may implement the read
system call to do that in this scenario. If assume that you will always get a full buffer, you may get a surprise when your application is run on the (hypothetical) new platform.
另一个问题是,有 种类型的流,您将肯定地 获得部分填充的缓冲区.套接字流,管道和控制台流是明显的示例.如果您使用文件流行为对应用程序进行编码,那么当有人针对另一种流运行该应用程序而导致失败时,您可能会感到讨厌.
Another issue is that there are some kinds of stream where you will definitely get partially filled buffers. Socket streams, pipes and console streams are obvious examples. If you code your application assuming file stream behavior, you could get a nasty surprise when someone runs it against another kind of stream ... and fails.
这篇关于如果有足够的数据,FileChannel.read读取的字节数会少于指定的字节数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!