Getting the character returned by read() in BufferedReader

佐手、 提交于 2019-11-29 13:24:10

问题


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?


回答1:


Just cast c to a char.

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();



回答2:


you could also read it into a char buffer

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

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

this will be more efficient than reading char per char




回答3:


Cast it to a char first:

response += (char) c;

Also (unrelated to your question), in that particular example you should use a StringBuilder, not a String.



来源:https://stackoverflow.com/questions/7771303/getting-the-character-returned-by-read-in-bufferedreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!