BufferOverflowException的原因是什么?

exception堆栈是

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
如何找到原因?

FileChannel #map :

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

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

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

 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:

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

因为你的字节数组大于缓冲区。

put(byte [] bytes)

我将检查你的file.length()并确保你的内存缓冲区可以实际写入。