gpt4 book ai didi

java - 带有 try-catch 的 for 循环在第一个索引处停止

转载 作者:行者123 更新时间:2023-12-02 05:10:18 25 4
gpt4 key购买 nike

String[] urls 包含字符串形式的 URL(代码读取每个 URL 的 inputStream)。

即使 for 循环中的退出条件是“i < urls.length”,我也无法迭代第一个索引(索引 0)之后的 String[] URL 的任何索引。

注意:当 String[] url 大小为 1 时它有效。我在 String[] url 大小为 2 时测试它,在这种情况下,只有第一个索引而不是第二个索引正在迭代。我只对 <body> 之间的内容感兴趣 block (因此 if (s.contains("<br>") )

关于为什么会发生这种情况有什么想法吗?

public void readData(String[] urls) {
for (int i=0; i<urls.length; i++) {
System.out.println(i); //for a String[] urls of size 2, only 0 gets printed.
//I want both 0 and 1 printed

String str="";

try {
URL url=new URL(urls[i]);
URLConnection conn=url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String s;

while (( s = in.readLine())!=null) {
if (s.contains("<br>")) {
str += s;
}
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(str); // for String[] urls of size 2,
//only the inputstream of urls' first index gets printed.
//I want both to be printed
}
}

编辑:这是我想阅读的 html 示例(String[] urls 的每个元素带来的内容)

<html>
<head>
<title>
Title
</title>
</head>
<body>
Name1 Age1 Hometown1<br>
Name2 Age2 Hometown2<br>
Name3 Age3 Hometown3<br>
</body>
</html>

最佳答案

我已经测试过这个,你的代码工作得很好。验证您从 url 提取的 HTML 并确保它包含“br”标记,因为这是您的条件,或者删除此条件,您将获得任何 html。

 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Main {
public static void readData(String[] urls) {
for (int i=0; i<urls.length; i++) {
String str="";
try {
URL url=new URL(urls[i]);
URLConnection conn=url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while (( s = in.readLine())!=null)
if (s.contains("<br>")) {
str += s;
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("Url No. " + i +"\n\n");
System.out.println(str +"\n");
}

}
public static void main(String[] args) {
String[] urls = {"http://google.com","http://google.com"};
readData(urls);

}
}

关于java - 带有 try-catch 的 for 循环在第一个索引处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27387784/

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