0

我一次读取 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);
   }

}

4

2 回答 2

2

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

于 2014-11-16T06:08:18.407 回答
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; 
  }

在这里,您还可以通过将参数大小与位置一起传递来使字节数组大小灵活。这里处理下溢异常。希望对您有所帮助;

于 2016-06-16T18:51:35.160 回答