2011-10-14 12 views
10

Come posso convertire un numero intero restituito da read() in un BufferedReader al valore del carattere effettivo e quindi aggiungerlo a una stringa? Lo read() restituisce il numero intero che rappresenta il carattere letto. Come quando faccio questo, non aggiunge il carattere reale nella stringa. Invece, aggiunge la rappresentazione intera stessa alla stringa.Ottenere il carattere restituito da read() in BufferedReader

int c; 
String result = ""; 

while ((c = bufferedReader.read()) != -1) { 
    //Since c is an integer, how can I get the value read by incoming.read() from here? 
    response += c; //This appends the integer read from incoming.read() to the String. I wanted the character read, not the integer representation 
} 

Cosa devo fare per ottenere i dati effettivi letti?

risposta

18

Basta trasmettere c a char.

Inoltre, non utilizzare mai += su un String in un ciclo. È O (n^2), piuttosto che l'attesa O (n). Utilizzare invece StringBuilder o StringBuffer.

int c; 
StringBuilder response= new StringBuilder(); 

while ((c = bufferedReader.read()) != -1) { 
    //Since c is an integer, cast it to a char. If it isn't -1, it will be in the correct range of char. 
    response.append((char)c) ; 
} 
String result = response.toString(); 
+0

Grazie per la risposta molto chiara! – Fattie

+1

@JoeBlow Grazie per il gentile commento. Per quanto riguarda la modifica, ritengo che la chiusura del lettore sia responsabilità di chiunque abbia creato il lettore. Perché non vediamo la creazione del lettore, chiuderlo non è appropriato qui, e oltre lo scopo della risposta .. – ILMTitan

3

cast a un char prima:

response += (char) c; 

anche (non correlato alla tua domanda), in quella particolare esempio è necessario utilizzare uno StringBuilder, non una stringa.

5

si potrebbe anche leggere in un buffer char

char[] buff = new char[1024]; 
int read; 
StringBuilder response= new StringBuilder(); 
while((read = bufferedReader.read(buff)) != -1) { 

    response.append(buff,0,read) ; 
} 

questo sarà più efficiente di lettura char per char

+1

qual è la "c"? –

Problemi correlati