2013-03-11 98 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

相關問題