gpt4 book ai didi

java - 来自 BufferedReader 时多行缺少第一个字符

转载 作者:行者123 更新时间:2023-12-02 02:48:13 26 4
gpt4 key购买 nike

我正在尝试打印 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

最佳答案

Here's BufferedReader.read() 的 javadoc 是这样写的:

Reads a single character.

Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

现在,让我们看一下代码:

while ((br.read()) != -1) {
System.out.println((br.readLine()));
}

您正在检查返回值read以查看是否已到达流末尾。但是,您没有打印该值(它没有存储在任何引用中,因此在比较后它会丢失)。理想情况下,您需要打印该值以及整行,例如:

String line;
while((line = br.readLine()) != null){
System.out.println(line);
}

关于java - 来自 BufferedReader 时多行缺少第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44238416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com