Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BufferOverflowException的原因是什么?_Java_Nio - Fatal编程技术网

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操作系统自动映射到内存中的文件,为什么缓冲区不是空的