异常堆栈是
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是什么原因
如何找到原因?
答案 0 :(得分:7)
此方法返回的映射字节缓冲区的位置为零,限制和容量大小;
换句话说,如果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)
答案 1 :(得分:0)