2

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
nobody
  • 1,909
  • 5
  • 31
  • 45
  • What do you mean by "*when the reading reaches the boundary*"? – aioobe Oct 06 '11 at 15:00
  • There's a limit upto which only the read should continue. The bytes after that shouldn't be read. That limit is the boundary. Updated question – nobody Oct 06 '11 at 15:05

2 Answers2

2

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);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Its a very Large file and I dont need the data beyond the upper limit. Actually the intention is to read the data from a specfied start position till specified end position. – nobody Oct 06 '11 at 15:12
  • There is a much simpler solution if you want to read/write a random area of a file. You can make it READ_ONLY or READ_WRITE. – Peter Lawrey Oct 06 '11 at 15:27
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483