Java ByteBuffer store char and extend the buffer if needed

Description

Java ByteBuffer store char and extend the buffer if needed

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.wrap("demo2s.com".getBytes());

    buf = putChar('J', buf);
   // buf = putChar('X', buf);

    String a = new String(buf.array());
    System.out.println(a);// www.ja  v a 2  s  .  co m

  }

  public static final int BLOCK_SIZE = 1024;

  /**
   * Add the character to the buffer, extending the buffer if needed
   * 
   * @return the same buffer if not extended, a new buffer if extended
   */
  public static final ByteBuffer putChar(char c, ByteBuffer buffer) {
    ByteBuffer localBuf = buffer;
    if (capacityRemaining(buffer) < 2) {
      localBuf = extendBuffer(buffer, BLOCK_SIZE);
    }
    localBuf.putChar(c);
    return localBuf;
  }

  /**
   * @return the remaining capacity in the buffer
   */
  private static int capacityRemaining(ByteBuffer buffer) {
    return buffer.limit() - buffer.position();
  }

  /**
   * @return a new buffer with the contents of the original buffer and extended by
   *         the size
   */
  private static ByteBuffer extendBuffer(ByteBuffer buffer, int size) {
    final ByteBuffer localBuffer = ByteBuffer.allocate(buffer.capacity() + size);
    System.arraycopy(buffer.array(), 0, localBuffer.array(), 0, buffer.position());
    localBuffer.position(buffer.position());
    return localBuffer;
  }
}



PreviousNext

Related