IoBufferUtil { public static ByteBuffer expandBuffer(ByteBuffer existingBuffer, int additionalRequired) { int pos = existingBuffer.position(); if ((pos + additionalRequired) > existingBuffer.limit()) { if ((pos + additionalRequired) < existingBuffer.capacity()) { existingBuffer.limit(pos + additionalRequired); } else { int newCapacity = existingBuffer.capacity() + additionalRequired ; java.nio.ByteBuffer newBuffer = java.nio.ByteBuffer.allocate(newCapacity); existingBuffer.flip(); newBuffer.put(existingBuffer); return newBuffer; } } return existingBuffer; }  static ByteBuffer expandBuffer(ByteBuffer existingBuffer, int additionalRequired); static boolean canAccomodate(ByteBuffer existingBuffer, int additionalLength);  }
@Test public void testIoBufferUtilExpand() { ByteBuffer buf = ByteBuffer.allocate(10); buf.put("12345".getBytes()); ByteBuffer newBuf = IoBufferUtil.expandBuffer(buf, 10); assertEquals(newBuf.capacity(), 20); newBuf.put("abcdefghij".getBytes()); newBuf.flip(); assertEquals(newBuf.remaining(), 15); assertEquals(newBuf.get(0), (byte)0x31); assertEquals(newBuf.get(5), (byte)0x61); assertEquals(newBuf.get(14), (byte)0x6A); }
@Test public void testIoBufferUtilExpandRetainSize() { ByteBuffer buf = ByteBuffer.allocate(10); buf.put("012345".getBytes()); ByteBuffer newBuf = IoBufferUtil.expandBuffer(buf, 4); assertEquals(buf, newBuf); assertEquals(buf.position(), 6); assertEquals(buf.position(), newBuf.position()); }