首页 文章

ByteBuffer和FileChannel只读取指定的字节数

提问于
浏览
2

我有一种情况,我继续阅读下面的ByteBuffer .

ByteBuffer buffer = MappedByteBuffer.allocateDirect(Constants.BUFFER_SIZE);

但是当读数到达边界时(当读取的剩余字节小于BUFFER_SIZE时),我只需要读取 boundaryLimit - FileChannel's current position .

意味着边界限制是x,当前位置是y,那么我需要从 y 读取字节,直到 x ,而不是超出该范围 .

我该如何实现这一目标?

我不想用新容量创建另一个实例 .

2 回答

  • 0

    它误导了我在这里使用MappedByteBuffer . 你应该用

    ByteBuffer buffer = ByteBuffer.allocateDirect(Constants.BUFFER_SIZE);
    

    如果您读取的字节数不足,则不成问题

    channel.read(buffer);
    buffer.flip();
    // Will be between 0 and Constants.BUFFER_SIZE
    int sizeInBuffer = buffer.remaining();
    

    编辑:从文件中的随机位置读取 .

    RandomAccessFile raf = 
    MappedByteBuffer buffer= raf.getChannel()
            .map(FileChannel.MapMode.READ_WRITE, start, length);
    
  • 2

    除了使用其他API(如FileInputStream,RandomAccessFile或MappedByteBuffer)之外,没有其他答案 . 如果你必须使用ByteBuffer,你必须在它发生后自己检测过度读取,并相应地进行补偿 .

相关问题