2012-01-24 10 views
6

Provo a mettere alcune stringhe su CharBuffer con la funzione CharBuffer.put() ma il buffer viene lasciato vuoto.CharBuffer.put() non funzionante

il mio codice:

CharBuffer charBuf = CharBuffer.allocate(1000); 
for (int i = 0; i < 10; i++) 
{ 
    String text = "testing" + i + "\n"; 
    charBuf.put(text); 
} 
System.out.println(charBuf); 

ho cercato di usare con clear() o rewind() dopo allocate(1000) ma questo non ha cambiato il risultato.

risposta

2

È necessario riavvolgere dopo aver messo negli oggetti, provare questo

CharBuffer charBuf = CharBuffer.allocate(1000); 
for (int i = 0; i < 10; i++) 
{ 
    String text = "testing" + i + "\n"; 
    charBuf.put(text); 
} 
charBuf.rewind(); 
System.out.println(charBuf); 
3

aggiungere una chiamata a rewind() destra dopo il ciclo.

3

Prova questo:

CharBuffer charBuf = CharBuffer.allocate(1000); 
for (int i = 0; i < 10; i++) 
{ 
    String text = "testing" + i + "\n"; 
    charBuf.put(text); 
} 
charBuf.rewind(); 
System.out.println(charBuf); 

Il dettaglio che ti manca è che la scrittura si muove il puntatore corrente alla fine dei dati scritti, in modo che quando si stampano fuori, è a partire dalla corrente del puntatore , che non ha scritto nulla.

3

È necessario flip() il buffer prima di poter leggere dal buffer. Il metodo flip() deve essere chiamato prima di leggere i dati dal buffer. Quando viene chiamato il metodo flip(), il limite viene impostato sulla posizione corrente e la posizione su 0. ad es.

CharBuffer charBuf = CharBuffer.allocate(1000); 
for (int i = 0; i < 10; i++) 
{ 
    String text = "testing" + i + "\n"; 
    charBuf.put(text); 
} 
charBuf.flip(); 
System.out.println(charBuf); 

Quanto sopra stamperà solo i caratteri nei buffer e non lo spazio non scritto nel buffer.