How to set fileChannel position

1.2k views Asked by At

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

}

2

There are 2 answers

0
user207421 On BEST ANSWER

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.

0
Vishal S On

I was also working a lot for reading the file as bytes. At first, i realized it would be great to have such a flexible mechanism that u can set the position of the file along with the byte size and finally end up with the below code.

public static byte[] bytes;
 public static ByteBuffer buffer;
 public static byte[] getBytes(int position)
  {
    try
    {
    bytes=new byte[10];
    buffer.position(position);
    buffer.get(bytes);
    }
    catch (BufferUnderflowException bue)
    {
      int capacity=buffer.capacity();    
      System.out.println(capacity);
      int size=capacity-position;
      bytes=new byte[size];
      buffer.get(bytes);

    } 
    return bytes; 
  }

Here u can also make the byte array size flexible by passing the parameter size along with the position. The underflow exception is handled here. Hopefully, it will help you;