在BufferedReader中获取read()返回的字符
如何将read()
in中返回的整数转换BufferedReader
为实际字符值,然后将其附加到String?将read()
返回一个代表字读整数。当我这样做时,它不会将实际字符附加到字符串中。而是将整数表示形式本身附加到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
}
我应该怎么做才能读取实际数据?
回答:
刚投到c
一个char
。
另外,不要使用过+=
一个String
在一个循环。它是O(n ^
2),而不是预期的O(n)。使用StringBuilder
或StringBuffer
代替。
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();
以上是 在BufferedReader中获取read()返回的字符 的全部内容, 来源链接: utcz.com/qa/429515.html