使用java.util.Scanner

时间:2015-10-27 22:40:21

标签: java java.util.scanner

我正在尝试从URL获取数据并将其转储到“content”实例变量中。 urlcontent都应该在构造函数中初始化。 hasNextLine()nextLine()也参与其中,但对Java来说是全新的,我无法理解。这是代码:

public class NewsFinder {

// Instance variables
private String url;
private String content;
private Scanner s;

// Getter methods
public String getUrl() {
    return url;
}

public String getContent() {
    return content;
}

// Constructor
public NewsFinder(String url) {
    this.url = url;

    try {
        Scanner s = new Scanner(new URL(url).openStream());
        if (s.hasNextLine()) {
            this.s = s.nextLine();

        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public boolean isInNews(Object o) {
    if (((String) o).contains(content)) {
        return true;
    } else {
        return false;
    }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

Scanner s = new Scanner(new URL(url).openStream());
if (s.hasNextLine()) {
    this.s = s.nextLine();
}

逻辑上,这部分代码应该替换为:

Scanner s = new Scanner(new URL(url).openStream());
while (s.hasNextLine()) {
    this.s += s.nextLine();
}

Personnaly,我会使用InputStreamBufferedReader来实现这一目标。

示例

URL url; InputStream is; BufferedReader br; String line; StringBuilder sb;
try{
    url = new URL("http://stackoverflow.com");
    is = url.openStream();
    br = new BufferedReader(new InputStreamReader(is));
    sb = new StringBuilder();

    while ((line = br.readLine()) != null){
        sb.append(line);
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    try{
        if(is != null){
        is.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}