Java BufferOverflowException 的原因是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20785409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:19:09  来源:igfitidea点击:

What is the cause of BufferOverflowException?

javanio

提问by fuyou001

The exception stack is

异常堆栈是

java.nio.BufferOverflowException
     at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:327)
     at java.nio.ByteBuffer.put(ByteBuffer.java:813)
            mappedByteBuffer.put(bytes);

The code:

编码:

randomAccessFile = new RandomAccessFile(file, "rw");
fileChannel = randomAccessFile.getChannel();
mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, file.length());

and call mappedByteBuffer.put(bytes);

并打电话 mappedByteBuffer.put(bytes);

What is the cause mappedByteBuffer.put(bytes)throws BufferOverflowException
How to find the cause ?

mappedByteBuffer.put(bytes)抛出BufferOverflowException 的原因是什么
如何查找原因?

采纳答案by Marko Topolnik

FileChannel#map:

文件通道#map:

The mapped byte buffer returned by this method will have a position of zero and a limit and capacity of size;

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

In other words, if bytes.length > file.length(), you should receive a BufferOverflowException.

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

To prove the point, I have tested this code:

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

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);
}

If and only iftrueis printed, this exception is thrown:

当且仅当true打印时,抛出此异常:

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

回答by XFCC

Supposedly because your byte array is bigger then the buffer.

据说是因为你的字节数组比缓冲区大。

put(byte [] bytes)

放置(字节 [] 字节)

I'd go by checking your file.length() and make sure that your memory buffer can actually be written.

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