fuyou001
fuyou001

Reputation: 1642

What is the cause of BufferOverflowException?

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

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

Upvotes: 22

Views: 55479

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

FileChannel#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.

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 if true is printed, this exception is thrown:

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

Upvotes: 10

XFCC
XFCC

Reputation: 384

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.

Upvotes: 0

Related Questions