异常堆栈是
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
.
为了证明这一点,我测试了这段代码:
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)