什么是缓冲区溢出异常的原因?

22

异常堆栈是

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)时,为什么会抛出BufferOverflowException异常?
如何找到原因?


你能展示 bytes 的声明吗? - Mehmet Sedat Güngör
bytes is byte[] bytes - fuyou001
@fuyou001,bytes 的大小怎么样? - tkroman
2
javadocs清楚地说明了为什么... - A4L
2个回答

9

FileChannel#map

此方法返回的映射字节缓冲区将具有零位置、大小和容量为size;

换句话说,如果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)

实际上,file.length是getter bytes.length。文件长度为128M。 - fuyou001
操作系统自动将文件映射到内存中,为什么缓冲区不为空? - fuyou001

0

可能是因为您的字节数组比缓冲区大。

put(byte [] bytes)

建议检查文件长度并确保内存缓冲区可以写入。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接