簡體   English   中英

java.net sourceCode閱讀器跳過行

[英]java.net sourceCode reader skipping lines

這段代碼用於下載html文件的源代碼,但它跳過了一些行,為什么會這樣?

import java.io.IOException;
import java.net.*;
import java.util.*;
import java.io.*;

public class downloadSource {
  private URL url;
  private URLConnection con;

  // Construct the object with a new URL Object resource
  downloadSource(String url) {
    try {
      this.url = new URL(url);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }

  // Returns an object instance 
  public BufferedReader SourceCodeStream() throws IOException {
    return new BufferedReader(new InputStreamReader(this.url.openStream()));
  }


  public void returnSource() throws IOException, InterruptedException {
    // FIX ENTRIE SOURCE CODE IS NOT BEING DWLOADED

    // Instinate a new object by assigning it the returned object from
    // the invoked SourceCodeStream method.

    BufferedReader s = this.SourceCodeStream();     
    if(s.ready()) { 
      String sourceCodeLine = s.readLine();
      Vector<String> linesOfSource = new Vector();
      while(sourceCodeLine != null) {
        sourceCodeLine = s.readLine();
        linesOfSource.add(s.readLine());            
      }

      Iterator lin = linesOfSource.iterator();
      while(lin.hasNext()) {
      }
    }
  }         
}   

每次迭代讀取兩行:

while(sourceCodeLine != null) {
      sourceCodeLine = s.readLine();

      linesOfSource.add(s.readLine());

  }

應該:

while(sourceCodeLine != null) {
      linesOfSource.add(sourceCodeLine);
      sourceCodeLine = s.readLine();
  }

第二個循環將第一行添加到linesOfSource ,該行也被跳過了:

String sourceCodeLine = s.readLine();

它缺少第一行以及所有其他行,因為您是從以下開始的:

String sourceCodeLine = s.readLine();

然后,在再次分配sourceCodeLine之前,請勿對其進行任何操作。 您的循環中還有另一個類似的問題。

相反,您可以執行以下操作:

String sourceCodeLine;
Vector<String> linesOfSource = new Vector();

while((sourceCodeLine = s.readLine()) != null) {
    linesOfSource.add(sourceCodeLine);
}

每次調用readLine()都會讀取一個新行,因此您需要保存每次執行readLine()時返回的信息,但是您並沒有這樣做。 嘗試這樣的事情:

while((tmp = s.readLine()) != null){
    linesOfSource.add(tmp);
}

你的問題在這里

 while(sourceCodeLine != null) {
        sourceCodeLine = s.readLine();

        linesOfSource.add(s.readLine());

    }

您讀取了兩行,並且僅向linesofSource添加了linesofSource

這樣可以解決問題。

while(sourceCodeLine != null) {    
        linesOfSource.add(sourceCodeLine); // We add line to list
        sourceCodeLine = s.readLine(); // We read another line
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM