在Java中从URL读取数据
我真的很困惑这个问题,需要澄清,只要有人能给一些。。。。很抱歉格式化了。在我尝试打开连接之后,程序似乎就停止了在Java中从URL读取数据,java,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.
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.");
}
也就是说,不会打印已建立的连接。您可以看到我正在尝试的代码和结果
您是否尝试过调试?如果打开连接出现问题,那么几秒钟后尝试连接程序将抛出异常。打印语句是我试图调试的,我没有得到任何信息。这个程序甚至都没有进入打印语句。你试过使用调试器吗?不明白,你是什么意思?你是说你不知道调试器是什么?天哪,真奇怪。我不知道我的问题是什么:/您是否尝试检查是否调用了run方法?如果是的话,让我们试着缩短你的代码,就像我的一样来测试它。问题仍然存在,然后尝试重新启动IDE…我从其他地方得到的输出显示线程正在运行,所以据我所知,确实调用了run。再次。。。。我建议使用调试器!你需要确定这里发生了什么,而不是依靠猜测/直觉。如果你的run方法被调用,那么你必须看到输出:startedtorun你看到了吗?别作客!让我们试着调试你的程序