Question

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.

Was it helpful?

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);

OTHER TIPS

There's no answer to this other than using another API such as a FileInputStream, RandomAccessFile, or MappedByteBuffer. If you have to use a ByteBuffer you will just have to detect the over-read yourself after it happens, and compensate accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top