获取 BufferedReader 中 read() 返回的字符
如何将 BufferedReader
中的 read()
返回的整数转换为实际字符值,然后将其附加到字符串? 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
}
我应该怎么做才能读取实际数据?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需将
c
转换为char
即可。另外,切勿在循环中的
String
上使用+=
。它是 O(n^2),而不是预期的 O(n)。请改用StringBuilder
或StringBuffer
。Just cast
c
to achar
.Also, don't ever use
+=
on aString
in a loop. It is O(n^2), rather than the expected O(n). UseStringBuilder
orStringBuffer
instead.您还可以将其读入字符缓冲区,
这比逐个字符读取字符更有效
you could also read it into a char buffer
this will be more efficient than reading char per char
首先将其转换为 char:
另外(与您的问题无关),在该特定示例中,您应该使用 StringBuilder,而不是 String。
Cast it to a char first:
Also (unrelated to your question), in that particular example you should use a StringBuilder, not a String.