Search code examples
javabytebytebufferfilechannel

How to set fileChannel position


I am reading in a file 510 bytes at a time. The bytes are in a byte buffer and I am reading them using a fileChannel.

Once I change the position, and it checks the case inside the while loop again but then jumps out the while loop. The total number of bytes is around 8000 bytes. How do I rewind to a specific position in the fileChannel without causing this error?

Heres my code:

File f = new File("./data.txt");

FileChannel fChannel = f.getChannel();
ByteBuffer bBuffer = ByteBuffer.allocate(510);

while(fChannel.read(bBuffer) > 0){

   //omit code



   if(//case){
       fChannel.position(3060);
   }

}


Solution

  • If your ByteBuffer is full, read() will return zero and your loop will terminate. You need to flip() your ByteBuffer, take data out of it, and then compact() it to make room for more data.