2013-03-11 153 views
0

我现在有后续的方法:JAVA:如何检查网站文档是否包含单词?

try { 
      URL url = new URL("http://auth.h.gp/HAKUNA%20MATATA.txt"); 
      Scanner s = new Scanner(url.openStream()); 
     } 
     catch(IOException ex) { 
      BotScript.log("Something went wrong =/ Error code:"); 
      ex.printStackTrace(); 
      stop(); 
     } 

但是,我怎么检查它是否包含一个字?我从来没有使用扫描仪,我发现这个片段在线。

谢谢。

+2

你总是可以从[阅读文档]开始(http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html),虽然你可能应该使用类似[ jsoup](http://jsoup.org/),而不是'Scanner'。 – 2013-03-11 23:28:31

回答

1

好吧,目前看起来不错。

然后,您可以使用扫描仪的next()方法获取每个单词。您还可以查询hasNext()以查看是否有其他令牌可用于避免错误。

boolean foundPumbaa = false; 
while (s.hasNext()) { 
    if (s.next().equalsIgnoreCase("pumbaa")) { 
     foundPumbaa = true; 
     System.out.println("We found Pumbaa"); // do something 
     break; 
    } 
} 
if (!foundPumbaa) { 
    System.out.println("We didn't find Pumbaa"); 
} 

编辑回应评论:
是的,你可以把文字变成String。最好的方法是使用BufferedReader

Java Tutorial, "Reading Directly from a URL"

下面的Java小程序使用的OpenStream()对URL http://www.oracle.com/得到一个输入 流。然后它会在输入流上打开一个 BufferedReader并从BufferedReader中读取 ,从而从URL读取。一切都读取复制到 标准输出流:

import java.net.*; 
import java.io.*; 

public class URLReader { 
    public static void main(String[] args) throws Exception { 

     URL oracle = new URL("http://www.oracle.com/"); 
     BufferedReader in = new BufferedReader(
     new InputStreamReader(oracle.openStream())); 

     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
    } 
} 

在实际的程序,而不是main throws Exception,你必须是一个try - catch块,赶上了IOException有的各种URLExceptions。但是这应该让你开始。

+0

谢谢!你知道我怎样才能将网页文字转换为字符串吗?那会是前者吗? 'String websource = s.next()'? – 2013-03-11 23:54:15

+0

@SteffenSørensen:看我的编辑 – wchargin 2013-03-11 23:57:21

相关问题