如何设置fileChannel位置

时间:2014-11-16 05:01:04

标签: java byte bytebuffer filechannel

我一次读取一个510字节的文件。字节在字节缓冲区中,我正在使用fileChannel读取它们。

一旦我改变位置,它会再次检查while循环内的情况,但然后跳出while循环。总字节数约为8000字节。如何在不导致此错误的情况下回退到fileChannel中的特定位置?

继承我的代码:

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 个答案:

答案 0 :(得分:2)

如果ByteBuffer已满,read()将返回零,您的循环将终止。您需要flip() ByteBuffer,从中获取数据,然后compact()以便为更多数据腾出空间。

答案 1 :(得分:0)

我还在为字节读取文件做了很多工作。起初,我意识到拥有这样一个灵活的机制可以很好,你可以设置文件的位置和字节大小,最后得到以下代码。

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

这里你也可以通过传递参数大小和位置来使字节数组大小灵活。这里处理了下溢异常。  希望它会对你有所帮助;