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?