As already mentioned, you can use the CharBuffer class, but allocating a new CharBuffer will only worsen your problem.
Instead, you can directly wrap your StringBuilder in a CharBuffer, since StringBuilder implements CharSequence:
Charset charset = StandardCharsets.UTF_8; CharsetEncoder encoder = charset.newEncoder();
EDIT: Duarte correctly indicates that the CharsetEncoder.encode method can return a buffer whose back array is larger than the actual data value, its capacity is greater than its limit. You must either read from ByteBuffer, or read the byte array from ByteBuffer, which is guaranteed to have the right size. In the latter case, two copies of bytes in memory cannot be avoided, albeit briefly:
ByteBuffer byteBuffer = encoder.encode(buffer); byte[] array; int arrayLen = byteBuffer.limit(); if (arrayLen == byteBuffer.capacity()) { array = byteBuffer.array(); } else {
source share