0
 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.

Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128

1 Answers1

2

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.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
  • You should do `read()`, `flip()`, `get()` (or something that implies it), and then `compact()`. `clear()` assumes you have processed all the data. `compact()` doesn't. – user207421 Apr 30 '12 at 00:06