BufferOverflowException的原因是什么?

时间:2013-12-26 13:05:32

标签: 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, "rw");
fileChannel = randomAccessFile.getChannel();
mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, file.length());

并致电mappedByteBuffer.put(bytes);

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

2 个答案:

答案 0 :(得分:7)

FileChannel#map

  

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

换句话说,如果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)

答案 1 :(得分:0)

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

put(byte [] bytes)

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