我正在尝试从URL获取数据并将其转储到“content”实例变量中。 url
和content
都应该在构造函数中初始化。 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;
}
}
有什么建议吗?
答案 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,我会使用InputStream和BufferedReader来实现这一目标。
示例强>
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();
}
}