获取BufferedReader中read()返回的字符 [英] Getting the character returned by read() in BufferedReader
问题描述
如何在 BufferedReader
中将 read()
返回的整数转换为实际字符值,然后将它附加到字符串? read()
返回表示读取字符的整数。当我这样做时,它不会将实际字符附加到String中。相反,它将整数表示本身附加到String。
How can I convert an integer returned by the read()
in a BufferedReader
to the actual character value and then append it to a String? The read()
returns the integer that represents the character read. How when I do this, it doesn't append the actual character into the String. Instead, it appends the integer representation itself to the 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
}
我该怎么做才能搞定读取的实际数据是什么?
What should I do to get the actual data read?
推荐答案
只需将 c
投射到 char
。
此外,请勿使用 + =
在循环中的字符串
上。它是O(n ^ 2),而不是预期的O(n)。改为使用 StringBuilder
或 StringBuffer
。
Also, don't ever use +=
on a String
in a loop. It is O(n^2), rather than the expected O(n). Use StringBuilder
or StringBuffer
instead.
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()返回的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!