0

I have a wrapper around the ByteBuffer class (because in my code, it is underlying structure for an entity). I want a ByteBuffer to store fixed sized entries in it and return null or throw an exception if we try to read at an offset where nothing was written. I've written the following code:

private static final int SIZE = 16; //Bytes
private static final int BBSIZE = 48 * SIZE;
ByteBuffer blockMap = ByteBuffer.allocateDirect(BBSIZE);

byte[] readAtOffset(final int offset) throws BufferUnderflowException,  
                                             IndexOutOfBoundsException {
    byte[] dataRead = new byte[SIZE];
    blockMap.position(offset);
    blockMap.get(dataRead);
    return dataRead;
}

void writeAtOffset(final int offset, final byte[] data)
        throws BufferOverflowException, IndexOutOfBoundsException, ReadOnlyBufferException     
{
     if (data.length != SIZE) {
         throw new IllegalArgumentException("Invalid data received");
     }
     blockMap.position(offset);
     blockMap.put(data);
}


public static void main(String[] args) {
    ByteBufferTests tests = new ByteBufferTests();
    System.out.println("At 0: " + tests.readAtOffset(0));       
}

Shouldn't this throw an exception as I haven't written anything to the buffer yet? What am I doing wrong?

user1071840
  • 3,522
  • 9
  • 48
  • 74

2 Answers2

2

To quote from the ByteBuffer JavaDoc:

The new buffer's position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero.

So, even though you haven't written to the buffer, the allocateDirect(...) method has (in a sense).

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
2

When you create a ByteBuffer it is full of zeros. It is full of the size you create it for. If you want to track which portions you have written to, you have to do this additionally, I suggest using an index number instead of a raw offset, and you can use a BitSet to see which portions were written to. An alternative is to make an assumption that a message won't start with nul bytes and if it does, it is corrupt/not present.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130