查看String时出现NullPointerException

时间:2014-05-06 04:57:10

标签: java string url nullpointerexception

我正在制作一个网络抓取工具,用于搜索包含短语的网页上的第一个(用户输入的)链接数。我爬得很好,但是当我试图查看链接是否包含短语时,我得到NullPointerExceptions。这是我用来做的代码:

private boolean linkContainsSearchFor(URL url){
    boolean ans = false;

    In urlIn = new In(url);
    String urlText = "";

    //if urlIn is null, get out now to avoid nullpointerexceptions
    if (urlIn == null)
        return ans;

    urlText = urlIn.readAll();
    System.out.println("urlText="+urlText);

    if(urlText.contains(searchFor)){
        ans = true;
        System.out.println("found a match!");
    }

    return ans;
}    

readAll()方法只是以文本形式读取整个网页,并将其作为一个巨大的String返回。那里应该没有任何错误,但这就是给我错误的界限。有什么想法吗?

编辑:这是错误屏幕。Here's the error screen

编辑#2:这是readAll()方法:

/**
 * Read and return the remainder of the input as a string.
 */
public String readAll() {
    if (!scanner.hasNextLine())
        return "";

    String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
    // not that important to reset delimeter, since now scanner is empty
    scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
    return result;
}

1 个答案:

答案 0 :(得分:0)

如果!scanner.hasNextLine()抛出异常,则表示扫描程序为空。