我正在尝试打印URL的内容,但第一个字符在许多行中丢失。如下面的输出“<”在DOCTYPE,head和html标签中缺少。
我尝试在while循环中使用readLine方法但是它显示了一个更奇怪的输出,其中DOCTYPE,头标记丢失,最后为null。
代码1:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class urlConnect {
public static void main(String[] args) throws Exception {
URL urlObj = new URL("https://soundcloud.com");
URLConnection conn = urlObj.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((br.read()) != -1) {
System.out.println((br.readLine()));
}
}
}
输出1:
!DOCTYPE html>
<html lang="en">
head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
...
...
...
</body>
/html>
代码2:
while ((br.readLine()) != null) {
System.out.println((br.readLine()));
}
输出2:
<head>
<link rel="dns-prefetch" href="//style.sndcdn.com">
<link rel="dns-prefetch" href="//api-v2.soundcloud.com">
<link rel="dns-prefetch" href="//secure.quantserve.com">
<link rel="dns-prefetch" href="//api.soundcloud.com">
<link rel="dns-prefetch" href="//i1.sndcdn.com">
<link rel="dns-prefetch" href="//i3.sndcdn.com">
<link rel="dns-prefetch" href="//wis.sndcdn.com">
<link rel="dns-prefetch" href="//pixel.quantserve.com">
...
...
...
<script type="text/javascript">window.__sc_version = "1495803442";
</body>
null
答案 0 :(得分:2)
Here's BufferedReader.read()
的javadoc,这就是它所说的:
读取单个字符。
<强>返回:强> 字符读取为0到65535(0x00-0xffff)范围内的整数,如果已到达流末尾则为-1
现在,我们来看看代码:
while ((br.read()) != -1) {
System.out.println((br.readLine()));
}
您正在检查返回值read
以查看是否已到达流的末尾。但是,您不打印该值(它不会存储在任何引用中,因此在比较后会丢失)。理想情况下,您需要将该值与整行一起打印,例如:
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
答案 1 :(得分:0)
这是完整的工作代码。我提到了Oracle Java文档https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
import java.util.*;
import java.lang.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class TestURL
{
public static void main (String[] args) throws java.lang.Exception
{
URL oracle = new URL("https://soundcloud.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}