Getting the character returned by read() in BufferedReader

后端 未结 3 1003
长情又很酷
长情又很酷 2020-12-30 06:46

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 rea

相关标签:
3条回答
  • 2020-12-30 07:05

    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();
    
    0 讨论(0)
  • 2020-12-30 07:10

    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.

    0 讨论(0)
  • 2020-12-30 07:17

    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

    0 讨论(0)
提交回复
热议问题