what if we exceed the capacity of allocating buffer in ByteBuffer.allocate(48) NIO package class in java

﹥>﹥吖頭↗ 提交于 2019-12-11 18:19:57

问题


 file = new RandomAccessFile("xanadu.txt", "rw");
        FileChannel channel = file.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(48);
        int byteReads = channel.read(buffer);

SO I am allocating 48 as a capacity in the Buffer. Now consider the txt file I am reading is of about 10MB , so logically it is crossing the buffer allocation size. But when we try to read, we will be able to read all the contents of the file despite the size. SO how this thing is possible.

I am new to this streaming field so may be my question seems to be very basic.


回答1:


The read call simply won't read more than 48 bytes.

Nothing will overflow, you'll just need to call read repeatedly until you've read all the data you're expecting.

This is stated in the ReadableByteChannel interface docs:

Reads a sequence of bytes from this channel into the given buffer.

An attempt is made to read up to r bytes from the channel, where r is the number of bytes remaining in the buffer, that is, dst.remaining(), at the moment this method is invoked.

You need to clear() the buffer after processing its content before passing it back to read.



来源:https://stackoverflow.com/questions/10373135/what-if-we-exceed-the-capacity-of-allocating-buffer-in-bytebuffer-allocate48-n

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