2011-10-14 16 views
10

如何將BufferedReader中的read()返回的整數轉換爲實際的字符值,然後將其附加到字符串? read()返回表示讀取字符的整數。當我這樣做時,它不會將實際字符附加到字符串中。相反,它將整數表示本身附加到String。獲取由BufferedReader中的read()返回的字符

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 
} 

我應該怎麼做來獲取實際數據?

回答

18

只需將c投射到char

另外,千萬不要在String上循環使用+=。它是O(n^2),而不是預期的O(n)。改爲使用StringBuilderStringBuffer

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

感謝非常明確的答案更高效! – Fattie

+1

@JoeBlow感謝您的評論。關於你的編輯,我覺得關閉讀者是誰創造讀者的責任。因爲我們沒有看到讀者的創作,關閉它在這裏是不適當的,超出了答案的範圍。 – ILMTitan

3

它轉換爲一個char第一:

response += (char) c; 

而且(無關你的問題),在那個特定的例子中,你應該使用StringBuilder,而不是一個字符串。

5

你也可以讀入一個字符緩衝區

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

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

這將是比讀炭炭每

+1

什麼是「c」? –

相關問題