BufferOverflowException的原因是什么?

编程入门 行业动态 更新时间:2024-10-26 08:22:08
本文介绍了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的原因是什么?

本文发布于:2023-11-26 03:20:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632426.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原因   BufferOverflowException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!