java.net sourceCode reader跳过行

时间:2012-02-01 13:50:35

标签: java

此代码用于下载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()) {
      }
    }
  }         
}   

4 个答案:

答案 0 :(得分:4)

每次迭代读取两行:

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

      linesOfSource.add(s.readLine());

  }

应该是:

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

第二个循环将第一行添加到linesOfSource,也被跳过:

String sourceCodeLine = s.readLine();

答案 1 :(得分:2)

缺少第一行和其他所有行,因为你从这开始:

String sourceCodeLine = s.readLine();

在再次分配之前,永远不要对sourceCodeLine做任何事情。你的循环中还有另一个类似的问题。

相反,你可以这样做:

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

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

答案 2 :(得分:2)

每次调用readLine()时,它都会读取一个新行,因此您需要保存每次执行readLine()时返回的信息,但您不是这样做的。尝试这样的事情:

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

答案 3 :(得分:0)

你的问题在这里

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

        linesOfSource.add(s.readLine());

    }

您阅读了两行,并只在linesofSource中添加了一行。

这将解决问题。

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