从Java中读取URL中的数据

时间:2017-05-13 03:11:16

标签: java

我对此问题感到非常困惑,只要有人能给出一些内容就需要澄清......我为格式化道歉。在我尝试打开连接之后,程序似乎只是暂停了。

public void run() {
        try {
            System.out.println("Started to run");

            //The first thing we do is connect with the website and instantiate a Scanner for the data.
            URL address = new URL("http://www.example.com");
            URLConnection connection = address.openConnection();
            Scanner scan = new Scanner(connection.getInputStream());
            System.out.println("Established connection");

            //We lop off the first 10 blank lines that we'll scan, plus the <body> tag. 
            for (int i = 0; i <= 10; i++) {
                scan.nextLine();
            }

            while (scan.hasNextLine()) {
                synchronized(lock) {//SYNCHRONIZE

                    //First, we check if we've reached the end.
                    String temp = scan.next(); 
                    if (temp.equals("</body>")) {
                        break; //If we have, cease processing.
                    }
                    year = Integer.parseInt(temp); 
                    boyName = scan.next(); boyPrevalence = scan.nextInt(); girlName = scan.next(); 
                    //(Handling the <br> HTML code.)
                    String next = scan.next();
                    next = next.replace("<br>", ""); 
                    girlPrevalence = Integer.parseInt(next);

                    //Now we update our almanac of boys' names for the given year.
                    if(boyNameMap.containsKey(year)) {
                        boyNameMap.get(year).put(boyName, boyPrevalence);
                    } else {
                        Map<String, Integer> tempmap = new HashMap<>();
                        tempmap.put(boyName, boyPrevalence);
                        boyNameMap.put(year, tempmap);
                    }

                    //And now we update our almanac of girls' names.
                    if(girlNameMap.containsKey(year)) {
                        girlNameMap.get(year).put(girlName, girlPrevalence);
                    } else {
                        Map<String, Integer> tempmap = new HashMap<>();
                        tempmap.put(girlName, girlPrevalence);
                        girlNameMap.put(year, tempmap);
                    }

                    System.out.println(year + "; " + boyName + "; " + boyPrevalence + "; "
                            + girlName + "; " + girlPrevalence);

                }//DESYNCHRONIZE
            }
            scan.close();
        }
        catch (IOException e) {
            System.out.println("File not found.");
        }

也就是说,“已建立的连接”从不打印。

1 个答案:

答案 0 :(得分:1)

您可以看到我正在尝试的代码和结果 enter image description here