Come molti hanno già suggerito, è possibile utilizzare la classe CharBuffer, ma l'assegnazione di una nuova CharBuffer avrebbe solo peggiorato il tuo problema
Invece, si può avvolgere direttamente il vostro StringBuilder in una CharBuffer, dal momento che StringBuilder implementa CharSequence:
Charset charset = StandardCharsets.UTF_8;
CharsetEncoder encoder = charset.newEncoder();
// No allocation performed, just wraps the StringBuilder.
CharBuffer buffer = CharBuffer.wrap(stringBuilder);
ByteBuffer bytes = encoder.encode(buffer);
EDIT: Duarte fa giustamente notare che il metodo CharsetEncoder.encode
può restituire un buffer il cui allineamento supporto è più grande il dato attuale - il significato, la sua capacità è maggiore del suo limite. È necessario leggere il ByteBuffer stesso o leggere un array di byte dal ByteBuffer che ha le dimensioni corrette. In quest'ultimo caso, non c'è nessun evitando avere due copie dei byte in memoria, anche se brevemente:
ByteBuffer byteBuffer = encoder.encode(buffer);
byte[] array;
int arrayLen = byteBuffer.limit();
if (arrayLen == byteBuffer.capacity()) {
array = byteBuffer.array();
} else {
// This will place two copies of the byte sequence in memory,
// until byteBuffer gets garbage-collected (which should happen
// pretty quickly once the reference to it is null'd).
array = new byte[arrayLen];
byteBuffer.get(array);
}
byteBuffer = null;
Il più vicino che si può ottenere è ottenere una matrice 'char []'. StringBuffer # getChars (int, int, char [], int) –
perché non utilizzare [CharBuffer] (http://docs.oracle.com/javase/7/docs/api/java/nio/CharBuffer.html)? E poi "charBuffer.array()"? – tolitius
Puoi chiarire perché è necessario memorizzare tutte queste grandi stringhe in memoria? È qualcosa su cui un utente sta aspettando? Potrebbe invece diventare un lavoro MapReduce o Spark? Mi chiedo solo se forse questa domanda è un sintomo di un odore di progettazione architettonica. – Vidya