当我调试下面的代码时,在“变量” View 中,response
和this.response
显示 http://www.google.com 的全部 1,779 行流式输入。但是,如果我想输出 this.response
到控制台 System.out.println(this.response.toString();
,它只输出最后几行。
最初我认为这是 String
的限制类(class)。为了测试这一点,我复制了 1,779 行并将它们分配给一个测试字符串变量。当我输出该测试字符串变量时,它会将所有 1,779 行输出到控制台。
我缺少什么this.respponse
和response
显示整个文档,但是当我输出其中任何一个时,我只得到最后几行?
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();
}
}
}
最佳答案
尝试使用 \n
而不是 \r
。
'\r' 是一个回车符 - 它将插入符号返回到行的开头,但不会开始新行,从而有效地覆盖当前行(或其部分)。
例如System.out.println("abcde\rfghi")
结果为 fghie
。
关于Java:为什么我不能将 StringBuffer 的 String 转换完整输出到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550530/