有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中从URL读取数据

我真的对这个问题感到困惑,需要尽快澄清,只要有人能给出一些。。。。很抱歉格式化了。在我尝试打开连接后,程序似乎就停止了

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) 个答案

  1. # 1 楼答案

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