运行了一半,控制台抛出这种异常,然后程序终止了。
Exception in thread "main" java.lang.NullPointerException
at SimpleAccess.getGoodLinks(SimpleAccess.java:27)
at SimpleAccess.urlList(SimpleAccess.java:18)
at SimpleAccess.main(SimpleAccess.java:60)
请问这个是什么样的错误?我的程序没有用线程,是不是要用线程呢?
还有请问高手,到底线程起的是一个什么样的作用,能解释下么?
Exception in thread "main" java.lang.NullPointerException
at SimpleAccess.getGoodLinks(SimpleAccess.java:27)
at SimpleAccess.urlList(SimpleAccess.java:18)
at SimpleAccess.main(SimpleAccess.java:60)
请问这个是什么样的错误?我的程序没有用线程,是不是要用线程呢?
还有请问高手,到底线程起的是一个什么样的作用,能解释下么?
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;import javax.swing.SwingUtilities;
public class SimpleAccess { public static ArrayList gl = new ArrayList(); public static ArrayList line = new ArrayList(); public static void urlList(String url) throws Exception {
if (!gl.contains(url)) {
gl.add(url);
for (int i = 0; i < gl.size(); i++) {
getGoodLinks((String) gl.get(i));
}
}
} public static void getGoodLinks(String str) throws Exception {
URL myURL = new URL(str);
URLConnection connection = myURL.openConnection(); if (connection.getContentType().toLowerCase().contains("html")) {
System.out.println("type is html");
System.out.println(str);
BufferedReader in = new BufferedReader(new InputStreamReader(myURL
.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Pattern p = Pattern.compile("(.*href=?[\"])(.*?)([\"].*)");
Matcher m = p.matcher(inputLine);
while (m.find()) {
URL u = new URL(myURL, m.group(2));
if (!gl.contains(u.toString())) {
gl.add(u.toString());
}
}
}
in.close(); }
} public int getSize() {
return gl.size();
} public static void main(String[] args) throws Exception {
SimpleAccess sa = new SimpleAccess();
urlList("http://www.csdn.com");
for (int i = 0; i < gl.size(); i++) {
System.out.println(gl.get(i));
}
System.out.println("finished");
int a = sa.getSize();
System.out.println(a);
}}这个程序是输入一个网页地址,比如http://www.csdn.com,然后找这个网页下面所有的超连接,包括超连接网页的超连接,但是要是html文件。
我用print把在搜索的网页打了出来,但是很奇怪,运行的好好的,突然就报这个错。
不知道怎么解决了。
紧急求助!谢谢大家!
(connection.getContentType()!=null) &&
connection.getContentType().toLowerCase().contains("html")
这样改了下,确实是对象null的问题,谢谢了。现在继续测试中..
1字符串变量未初始化;
2接口类型的对象没有用具体的类初始化,比如:
List lt;会报错
List lt = new ArrayList();则不会报错了
3当一个对象的值为空时,你没有判断为空的情况。
你可以试着把下面的代码前加一行代码:
if(rb!=null && rb!="")
改成:
if(rb==null);
if(rb!==null&&rb!="")