Java BufferOverflowException的原因是什么?
异常堆栈是Java BufferOverflowException的原因是什么?,java,nio,Java,Nio,异常堆栈是 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, "
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(字节)代码>
什么是引发BufferOverflowException的原因
如何找到原因?:
此方法返回的映射字节缓冲区的位置为零,大小限制和容量为
换句话说,如果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()文件,确保你的内存缓冲区可以被写入 你能显示字节的声明吗?字节是字节[]bytes@fuyou001,那么字节的大小如何?清楚地说明了为什么…事实上,file.lenght是getter bytes.length。file lenghts是128m操作系统自动映射到内存中的文件,为什么缓冲区不是空的