繁体   English   中英

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

[英]for loop with try-catch stopping at first index

String [] url包含URL作为字符串(代码读取每个URL的inputStream)。

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

注意:当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 [] url的每个元素都带到什么)

<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);

            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM