获取BufferedReader中read()返回的字符

时间:2011-10-14 17:27:04

标签: java bufferedreader

如何将read()BufferedReader返回的整数转换为实际字符值,然后将其附加到字符串? read()返回表示读取字符的整数。当我这样做时,它不会将实际字符附加到String中。相反,它将整数表示本身附加到String。

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
}

我该怎么做才能读取实际数据?

3 个答案:

答案 0 :(得分:20)

只需将c投射到char

此外,请勿在{{1​​}}循环中使用+=。它是O(n ^ 2),而不是预期的O(n)。请改用StringStringBuilder

StringBuffer

答案 1 :(得分:5)

您也可以将其读入char缓冲区

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

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

这比阅读char char

更有效

答案 2 :(得分:3)

首先将它转换为char:

response += (char) c;

另外(与您的问题无关),在该特定示例中,您应该使用StringBuilder,而不是String。