2015-02-26 17 views
10

Qualcuno sa come convertire ByteBuffer in byte [] array? Ho bisogno di ottenere array di byte dal mio ByteBuffer. Quando corro bytebuffer.hasArrray() restituisce no. Ogni domanda che ho guardato fino ad ora è la conversione di array di byte in byteBuffer, ma ho bisogno del contrario. Grazie.Converti ByteBuffer in byte array java

+0

Hai provato 'byteBuffer.array()'? –

+0

@JohnnyWiller: fallirà ... hasArray sta restituendo 'false'. –

+0

Sì, ho fatto senza successo. – Powisss

risposta

23

ByteBuffer espone il grosso metodo get(byte[]) che trasferisce i byte dal buffer nell'array. Avrai bisogno di istanziare una serie di lunghezza pari al numero di byte rimanenti nel buffer.

ByteBuffer buf = ... 
byte[] arr = new byte[buf.remaining()]; 
buf.get(arr); 
+0

Gli anwers di codice sono normalmente migliorati aggiungendo del testo che spiega cosa sta facendo il codice - puoi aggiungere un po 'di testo per spiegare all'OP? –

+0

Grazie amico mio! – Powisss

1

Se hasArray() segnala false, chiamare array() genererà un'eccezione.

In tal caso, l'unico modo per ottenere i dati in un byte[] è di assegnare un byte[] e copiare i byte al byte[] utilizzando get(byte) o simili.

-1

Semplice esempio di opere.

ByteBuffer bb1 = ByteBuffer.wrap("hello world".getBytes()); 
    System.out.println(bb1.hasArray()); 
    System.out.println(new String(bb1.array())); 

Tuttavia si dice che l'array restituisce false. Può essere solo una lettura.

/** 
* Tells whether or not this buffer is backed by an accessible byte 
* array. 
* 
* <p> If this method returns <tt>true</tt> then the {@link #array() array} 
* and {@link #arrayOffset() arrayOffset} methods may safely be invoked. 
* </p> 
* 
* @return <tt>true</tt> if, and only if, this buffer 
*   is backed by an array and is not read-only 
*/ 
public final boolean hasArray() { 
    return (hb != null) && !isReadOnly; 
}