2010-11-20 45 views
0

我需要從特定行讀取URL html頁面中的行。閱讀url數據特定行java

現在,我有以下代碼:

u = new URL("http://s.ll/message/" + counter); 

is = u.openStream(); // throws an IOException 

dis = new DataInputStream(new BufferedInputStream(is)); 

while ((s = dis.readLine()) != null) { 
    if (s.contains('%') 
     ... 
} 

我知道這個內容會不會是50前行。

我該如何閱讀這一行?

這是讀取網址最快的方法嗎?

回答

0

你在正確的軌道上。要從URL中讀取數據,最簡單的方法就是使用URL對象。對於更復雜的HTTP通信任務,您可能會考慮HTTPClient

您正在使用的方法 DataInputStream.readLine()已棄用,因爲您無法提供從字節轉換爲字符串時使用的字符集。

我會做這樣的:

u = new URL("http://s.ll/message/" + counter); 

is = u.openStream(); // throws an IOException 

// XXX notice the charset set to utf-8 here. 
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8")); 

while ((s = reader.readLine()) != null) { 
    if (s.contains('%') 
     ... 
} 

查找第50行要求你跳到它。由於您無法知道流的哪一個字節偏移,第50個'\ n'(或'\ r'或'\ r \ n'取決於Unix,Mac或Windows換行符) - 您只需從開始。

3

我怎樣才能從這一行讀取?

當計數低於50時,計數直線並忽略直線。除了讀取直線和計算直線外,沒有什麼神奇的方法直接前進到第50行。無論如何,流必須被讀取。

這是讀取網址最快的方法嗎?

取決於。然而,更常見的方法是BufferedReader + InputStreamReader其中您指定網頁編碼的字符集以避免mojibake

+0

+1 for mojibake! – systempuntoout 2010-11-20 22:51:01