Java:为什么我不能将从StringBuffer转换的String输出到控制台中呢?

时间:2015-04-09 23:02:01

标签: java string stringbuffer system.out

当我调试下面的代码时,在“变量”视图中,responsethis.response都显示来自http://www.google.com的整个1,779行流输入。但是,如果我想使用this.responseSystem.out.println(this.response.toString();输出到控制台,则只输出最后几行。

最初我认为这是String类的限制。为了测试这一点,我复制了1,779行并将它们分配给测试String变量。当我输出该测试字符串变量时,它将所有1,779行输出到控制台就好了。

我在this.respponseresponse显示整个文档的地方错过了什么,但当我输出其中任何一个时,我只得到最后几行?

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

    }
}

2 个答案:

答案 0 :(得分:1)

尝试使用\n代替\r

'\ r'是回车符 - 它将插入符号返回到行的开头,但不会启动新行,从而有效地覆盖当前行(或部分行)。

e.g。 System.out.println("abcde\rfghi")会产生fghie

答案 1 :(得分:0)

对于打印内容,我对Java没有任何限制。问题可能在于您的控制台。您使用Eclipse或其他IDE来开发和运行应用程序吗?如果是 - 那么默认情况下,默认情况下,旧的行将在Eclipse Run Console上截断。这条线也是红色的,

this.response = response.toString();