Search code examples
javaexceptioncomparememory-mapped-filesbytebuffer

Buffer Underflow Exception java


I have a class-comparator, that compares my files with different algoritms. In this part I try to get a byte block from file to compare with another file's block.

public class CompareFiles {

    private byte[] getBytesFromFile(File file) throws IOException {
    long BUFFER_SIZE = 4 * 1024;
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    FileChannel fc = raf.getChannel();
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, BUFFER_SIZE);
    byte[] bytes = new byte[(int) fc.size()];
    buffer.get(bytes);
    buffer.clear();
    return bytes;
    }
}

If I try to use one on big files I get

Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.DirectByteBuffer.get(Unknown Source)
at java.nio.ByteBuffer.get(Unknown Source)

I guess, i make mistake in my minds and get compare blocks in wrong way.


Solution

  • The problem is you are mapping in a small region, e.g. 4 KB and then attempting to read the whole file which I guess is more than 4 KB.

    BTW, you should always close a file once you have finished with it in a finally block or with a try-with-resource block. buffer.clear(); doesn't do anything in this case.

    The main advantage of using memory mapped files and avoiding needing to copy the data into a byte[]. If you need a byte[] just read it into a byte[] directly. If you want an optimal solution, try to avoid using a byte[].