Search code examples
javastringstringbuffersystem.out

Java: Why can't I output a String converted from StringBuffer to the console in it's entirety?


When I debug the code below, in the "Variables" view, both response and this.response show the entire 1,779 lines of streamed input from http://www.google.com. If, however, I want to output this.response to the console with System.out.println(this.response.toString();, it only outputs the last few lines.

Initially I thought it was a limitation of the String class. To test this I copied the 1,779 lines and assigned them to a test String variable. When I output that test String variable, it output all 1,779 lines to the console just fine.

What am I missing where both this.respponse and response show the entire document, but when I go to output either of them, I only get the last few lines?

public class ClassC {
    private String url = "http://www.google.com";
    private URL URL;
    private HttpURLConnection con;
    private String response;
    public static void main(String[] args) {
        new ClassC();
    }

    public ClassC() {
        try {
            URL = new URL(url);
            con = (HttpURLConnection) URL.openConnection();

            InputStream is = con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer response = new StringBuffer();
            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
                System.out.println(response.toString());
            }
            rd.close();
            this.response = response.toString();
            System.out.println(this.response);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Solution

  • Try \n instead of \r.

    '\r' is a carriage return - it returns the caret to the start of the line, but doesn't start a new line, effectively overwriting the current line (or parts of it).

    e.g. System.out.println("abcde\rfghi") results in fghie.