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

StringreadString(ByteBuffer buf, int length)
Read string from ByteBuffer
byte[] buffer = new byte[length];
buf.get(buffer);
return new String(buffer);
StringreadString(ByteBuffer buff)
read String
int size = readVarInt(buff);
byte[] bytes = new byte[size];
buff.get(bytes);
return new String(bytes, StandardCharsets.UTF_8);
StringreadString(ByteBuffer buff, int len)
Read a string.
char[] chars = new char[len];
for (int i = 0; i < len; i++) {
    int x = buff.get() & 0xff;
    if (x < 0x80) {
        chars[i] = (char) x;
    } else if (x >= 0xe0) {
        chars[i] = (char) (((x & 0xf) << 12) + ((buff.get() & 0x3f) << 6) + (buff.get() & 0x3f));
    } else {
...
StringreadString(ByteBuffer buffer)
read String
int i = readVarInt(buffer);
if (i > MAX_STRING_LENGTH * 4) {
    throw new IOException("The received encoded string buffer length is longer than maximum allowed (" + i
            + " > " + MAX_STRING_LENGTH * 4 + ")");
if (i < 0) {
    throw new IOException("The received encoded string buffer length is less than zero! Weird string!");
try {
    byte[] bytes = new byte[i];
    buffer.get(bytes);
    String s = new String(bytes, StandardCharsets.UTF_8);
    if (s.length() > MAX_STRING_LENGTH) {
        throw new IOException("The received string length is longer than maximum allowed (" + s.length()
                + " > " + MAX_STRING_LENGTH + ")");
    } else {
        return s;
} catch (UnsupportedEncodingException e) {
    throw new IOException(e);
StringreadString(ByteBuffer buffer)
read String
byte[] data = new byte[256];
int i = 0, value = 0;
for (i = 0; (i < data.length) && ((value = buffer.get()) > 0); ++i) {
    data[i] = (byte) value;
return new String(data, 0, i);
StringreadString(ByteBuffer byteBuffer)
read String
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte b = -1;
while ((b = byteBuffer.get()) != 0) {
    bytes.write(b);
return new String(bytes.toByteArray());
StringreadString(ByteBuffer byteBuffer)
read String
int len = byteBuffer.getInt();
if (len <= 1) {
    return "";
} else {
    byte[] b = new byte[len];
    byteBuffer.get(b);
    return new String(b, 0, len - 1);
StringreadString(ByteBuffer logBuf)
Read a string from the log.
return new String(readByteArray(logBuf));
StringreadString(final ByteBuffer buffer, final String encoding)
Translate the given buffer into a string
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return new String(bytes, encoding);
Stringstring(ByteBuffer b, Charset charset)
string
return new String(b.array(), b.arrayOffset() + b.position(), b.remaining(), charset);