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

Car*_*ven 10 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
}
Run Code Online (Sandbox Code Playgroud)

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

ILM*_*tan 21

刚刚投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 c isn't -1, it will be in the correct range of char.
    response.append( (char)c ) ;  
}
String result = response.toString();
Run Code Online (Sandbox Code Playgroud)


rat*_*eak 5

你也可以将它读入char缓冲区

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

    response.append( buff,0,read ) ;  
}
Run Code Online (Sandbox Code Playgroud)

这比读取char char更有效