2013-12-12 30 views
1

我有一個快速的問題,我很難找出答案。我想逐行閱讀一個html文件,但我想跳過html標題。因此,我想我可以在打標籤後開始閱讀文本。到目前爲止,我已經創建了:如何跳過html標題並在找到html標籤後開始閱讀?

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

StringBuilder string = new StringBuilder(); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     //if (line.startsWith("<html>")) 
     System.out.println("This is each line: " + line); 
     string.append(line + "\n"); 

基本上,我想讀的線條和直接跳過線,直到我看到HTML標記。在此之前的一切將成爲一個標題,我不需要那個。

+1

有作爲HTML頭沒有這樣的事情。有HTTP標頭。你是這個意思嗎?爲什麼使用套接字而不是正確的HTTP客戶端發出HTTP請求? –

+0

@SotiriosDelimanolis是的。那就是我的意思。我道歉。我目前正在調用一個方法創建一個HTTP請求。我打算髮布整個代碼。 – Brandon

+0

雖然搜索html標籤可能適用於您的情況,但請記住,一般來說,HTML開始標籤是可選的,因此可能根本不會出現在任意HTML文件中。另一方面,HTTP標頭真的很容易跳過。只需從頭開始閱讀這些文字,直到您找到空行。隨後HTML將立即開始。 – Alohci

回答

0

如何這樣的事情 -

boolean htmlFound = false;      // Have we found an open html tag? 
StringBuilder string = new StringBuilder();  // Back to your code... 
String line; 
while ((line = reader.readLine()) != null) { 
    if (!htmlFound) {        // Have we found it yet? 
    if (line.toLowerCase().startsWith("<html")) { // Check if this line opens a html tag... 
     htmlFound = true;       // yes? Excellent! 
    } else { 
     continue;         // Skip over this line... 
    } 
    } 
    System.out.println("This is each line: " + line); 
    string.append(line + "\n"); 
} 
相關問題