Search code examples
javafile-ioniobytebufferfilechannel

ByteBuffer and FileChannel reading only the specified number of bytes


I have a situation where in I keep reading with a ByteBuffer as below.

 ByteBuffer buffer = MappedByteBuffer.allocateDirect(Constants.BUFFER_SIZE);

But when the reading reaches the boundary (when the remaining bytes to read is less than BUFFER_SIZE) I need to read only the boundaryLimit - FileChannel's current position .

Means the boundary limit is x and current positions is y, then I need to read bytes from y till x and not beyond that.

How do I achieve this ?

I dont want to create another instance with new capacity.


Solution

  • Its misleading to use MappedByteBuffer here. You should use

    ByteBuffer buffer = ByteBuffer.allocateDirect(Constants.BUFFER_SIZE);
    

    If you read less than a full amount of bytes its not a problem

    channel.read(buffer);
    buffer.flip();
    // Will be between 0 and Constants.BUFFER_SIZE
    int sizeInBuffer = buffer.remaining(); 
    

    EDIT: To read from a random location in a file.

    RandomAccessFile raf = 
    MappedByteBuffer buffer= raf.getChannel()
            .map(FileChannel.MapMode.READ_WRITE, start, length);