【问题标题】:How to set fileChannel position如何设置文件通道位置
【发布时间】:2016-06-17 02:51:35
【问题描述】:

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

}

【问题讨论】:

  • 如果你需要随机访问,我建议内存映射文件。您可以在 Java 中轻松地为最多 2 GB 的数据执行此操作(并且它不使用堆空间来存储数据)

标签: java byte bytebuffer filechannel


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2017-04-22
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多