BufferOverflowException的原因是什么? [英] What is the cause of BufferOverflowException?

查看:2005
本文介绍了BufferOverflowException的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异常堆栈是

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) throws BufferOverflowException


如何查找原因?

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

推荐答案

FileChannel #map


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

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

换句话说,如果 bytes.length> file.length <),你应该收到 BufferOverflowException

In other words, if bytes.length > file.length(), you should receive a 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);
}

当且仅当 true ,抛出此异常:

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

这篇关于BufferOverflowException的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆