BufferOverflowException的原因是什么?

  发布于 2023-02-08 09:19

异常堆栈是

java.nio.BufferOverflowException
     at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:327)
     at java.nio.ByteBuffer.put(ByteBuffer.java:813)
            mappedByteBuffer.put(bytes);

代码:

randomAccessFile = new RandomAccessFile(file, "rw");
fileChannel = randomAccessFile.getChannel();
mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, file.length());

并打电话 mappedByteBuffer.put(bytes);

是什么原因 mappedByteBuffer.put(bytes)抛出BufferOverflowException
如何查找原因?

1 个回答
  • FileChannel #map:

    此方法返回的映射字节缓冲区的位置为零,限制和大小容量;

    换句话说,如果bytes.length > file.length(),你应该收到一个BufferOverflowException.

    为了证明这一点,我测试了这段代码:

    File f = new File("test.txt");
    try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
      FileChannel ch = raf.getChannel();
      MappedByteBuffer buf = ch.map(MapMode.READ_WRITE, 0, f.length());
      final byte[] src = new byte[10];
      System.out.println(src.length > f.length());
      buf.put(src);
    }
    

    当且仅当 true打印时,抛出此异常:

    Exception in thread "main" java.nio.BufferOverflowException
    at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:357)
    at java.nio.ByteBuffer.put(ByteBuffer.java:832)
    

    2023-02-08 09:24 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有