2012-02-01 49 views
0

此代码是下载HTML文件的源代码 ,但它跳过一些行为什么会发生?java.net sourceCode阅读器跳过行

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

这读取每个迭代的两行:

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

     linesOfSource.add(s.readLine()); 

    } 

应该是:

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

这第二个循环将第一行linesOfSource也被跳过:

String sourceCodeLine = s.readLine(); 
2

它缺少第一线,和所有其他行,因为你这个开始了:

String sourceCodeLine = s.readLine(); 

它再次分配之前然后从不sourceCodeLine做任何事情。你的循环中有另一个类似的问题。

相反,你可以做这样的事情:

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

while((sourceCodeLine = s.readLine()) != null) { 
    linesOfSource.add(sourceCodeLine); 
} 
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 
    } 
2

每次调用readLine()它读取一个新行,所以你需要将它保存返回每次执行readLine()时间的信息,但是你是不是做那个时候。尝试这样的代替:

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