Java Utililty Methods ByteBuffer from String

List of utility methods to do ByteBuffer from String

Description

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

Method

ByteBufferasByteBuffer(String data)
as Byte Buffer
try {
    return ByteBuffer.wrap(data.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
    throw new UnsupportedOperationException(e);
ByteBufferasByteBuffer(String s)
as Byte Buffer
if (null == s) {
    return null;
if (s.length() < 1024) { 
    return isASCII(s) ? US_ASCII.encode(s) : UTF_8.encode(s);
} else {
    return UTF_8.encode(s);
ByteBufferstringToByteBuffer(String data)
string To Byte Buffer
return ByteBuffer.wrap(data.getBytes());
ByteBufferstringToByteBuffer(String string)
string To Byte Buffer
ByteBuffer bb = null;
try {
    bb = ByteBuffer.wrap(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    throw new Error();
return bb;
...
ByteBufferstringToNullTerminatedByteBuffer(String s)
Converts a String into a direct ByteBuffer, after adding a null character at the end of the String
int len = s.length() + 1;
ByteBuffer buf = directByteBuffer(len);
buf.put(s.getBytes());
buf.put((byte) 0);
buf.flip();
return buf;
ByteBuffertoByteBuffer(final String s)
Converts a string into bytes in the UTF-8 character set.
return DEFAULT_CHARSET.encode(CharBuffer.wrap(s));
ByteBuffertoByteBuffer(String hexStr)
to Byte Buffer
if (hexStr == null || hexStr.length() == 0) {
    return null;
if (hexStr.length() % 2 != 0) {
    throw new IllegalArgumentException("Invalid hex value.");
byte[] ba = new byte[hexStr.length() / 2];
for (int i = 0; i < ba.length; i++) {
...
ByteBuffertoByteBuffer(String s)
Converts the given String into a 0-terminated, direct byte buffer.
byte bytes[] = s.getBytes();
ByteBuffer buffer = createByteBuffer(bytes.length + 1);
buffer.put(bytes);
buffer.put((byte) 0);
buffer.rewind();
return buffer;
ByteBuffertoByteBuffer(String value)
Convert the given String to a byte[] value using UTF-8 and wrap in a ByteBuffer.
return ByteBuffer.wrap(toBytes(value));
ByteBuffertoByteBuffer(String value)
to Byte Buffer
return ByteBuffer.wrap(value.getBytes("utf-8"));