Java Utililty Methods ByteBuffer to String

List of utility methods to do ByteBuffer to String

Description

The list of methods to do ByteBuffer to String are organized into topic(s).

Method

StringgetString(ByteBuffer buf, Charset encoding)
Converts all remaining bytes in the buffer a String using the specified encoding.
return getString(buf, 0, buf.remaining(), encoding);
StringgetString(ByteBuffer buf, int length, String charsetName)
This is a relative get String method for ByteBuffer because it doesn't have one (but should!).
try {
    return new String(getBytes(buf, length), charsetName);
} catch (UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
StringgetString(ByteBuffer buffer)
get String
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
try {
    charset = Charset.forName("UTF-8");
    decoder = charset.newDecoder();
    charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
    return charBuffer.toString();
...
StringgetString(ByteBuffer buffer)
get String
StringBuilder sb = new StringBuilder(buffer.limit());
while (buffer.remaining() > 0) {
    char c = (char) buffer.get();
    if (c == 0)
        break;
    sb.append(c);
return sb.toString();
...
StringgetString(ByteBuffer buffer, int length)
get String
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
    builder.append((char) buffer.get());
return builder.toString();
StringgetString(ByteBuffer buffer, int offset, int length, String encoding)
Create String offset from position by offset upto length using encoding, and position of buffer is moved to after position + offset + length
byte[] b = new byte[length];
buffer.position(buffer.position() + offset);
buffer.get(b);
try {
    return new String(b, 0, length, encoding);
} catch (UnsupportedEncodingException uee) {
    throw new RuntimeException(uee);
StringgetString(ByteBuffer buffer, int size)
get String
byte[] result = new byte[size];
buffer.get(result);
return new String(result, CHARSET);
StringgetString(ByteBuffer buffer, int size)
get String
assert (0 < size);
assert (buffer.capacity() - buffer.position() >= size);
ByteBuffer buf = ByteBuffer.allocate(size);
buffer.get(buf.array(), 0, size);
try {
    return Charset.defaultCharset().newDecoder().decode(buf).toString().trim();
} catch (Exception e) {
    e.printStackTrace();
...
StringgetString(ByteBuffer buffer, String charFormat)
get String
String result;
int length;
if (charFormat == "UTF-16LE") {
    length = buffer.order(ByteOrder.LITTLE_ENDIAN).getInt();
} else {
    length = buffer.order(ByteOrder.LITTLE_ENDIAN).getShort();
int bufferPosition = buffer.position();
...
StringgetString(ByteBuffer byteBuffer, int size)
get String
byte[] bytes = new byte[size];
byteBuffer.get(bytes);
return new String(bytes, Charset.defaultCharset());