Search code examples
javaniobytebuffermappedbytebuffer

IndexOutOfBoundsException when use MappedByteBuffer


I am thinking of using MappedByteBuffer to store/load some data to a file. Let's assume I have field A of type long and field B of a string looks like below when serialized: A(long) | B(string)

Now i want to write and read to it. here is a piece of sample code:

RandomAccessFile file = new RandomAccessFile(dataPath.toString(), "rw");
    MappedByteBuffer mbb = file.getChannel().map(FileChannel.MapMode
            .READ_WRITE, 0, 256);
    long num = 500;
    mbb.putLong(0, num); // (1) first write the long value at beginning
    String str = "Hello World!";
    byte[] input = str.getBytes();
    //then write a string
    mbb.put(input, 8, input.length); // (2) IndexOutOfBoundsException

So later I can retrieve long by calling mbb.getLong(0)
and mbb.get(outputArray,8,outputArray.length)

but now i am failing at place (2). any suggestions?


Solution

  • Try

    mbb.put(destArray, 0, sourceArray.length)
    

    I don't think you want to start writing at an 8 byte offset, otherwise you'd be trying to write 8 bytes over the lenght of the array.