【发布时间】:2014-12-09 20:03:36
【问题描述】:
String[] urls 包含作为字符串的 URL(代码读取每个 URL 的 inputStream)。
即使 for 循环中的退出条件是“i
注意:它在 String[] urls 大小为 1 时有效。我在 String[] urls 大小为 2 时对其进行测试,在这种情况下,只有第一个索引而不是第二个索引在迭代。而且我只对<body> 块之间的内容感兴趣(因此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。甚至可能是System.out.println(urls.length),只要它> 0,它就应该迭代。
-
为什么不删除循环并使用一个 URL 进行测试。之后,请确保关闭连接。最后,如果可行,请考虑如何完成其余 URL 的整个过程
-
共享堆栈跟踪(如果有)
-
你能给我们看看
readData的电话吗?另外,请澄清您所说的“我无法迭代......”是什么意思 - 您到底看到了什么您没有预料到的? -
@Kevin 我只想补充一点,
System.out.println(urls.length)应该在 for 循环之前 :)
标签: java for-loop try-catch inputstream bufferedreader