2013-08-02 41 views
0

這是我的代碼。爲什麼我的BufferedInputStream不下載某些文件?

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read 
{ 
    download.removeMouseListener(m); 
    /*speed.setText(String.valueOf(count));*/ 
    if (time >= time2){ // every second , set kb/s 
     long initTimeInSeconds = initTime/1000000000; 
     long currentTimeInSeconds = time/1000000000; 
     speed.setText(String.valueOf((fout.getChannel().size()/1024)/(currentTimeInSeconds-initTimeInSeconds) + "KB/s")); // set kb/s 
     time2 = System.nanoTime() + 1000000000; 
    } 

    progress.setValue((int) fout.getChannel().size());//update progress bar 
    fout.write(data, 0, count); // write the data to the file 
    time = System.nanoTime(); 
} 

本質上,下載代碼僅僅是這樣的:

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read 
{ 
    fout.write(data, 0, count); // write the data to the file 
    time = System.nanoTime(); 
} 

byte data[] = new byte[16384]; 
BufferedInputStream in = null; 
in = new BufferedInputStream(url.openStream()); 
int count = 0; 

不知怎的,這個代碼不下載特定文件,例如該文件。 http://nmap.org/dist/nmap-6.40-setup.exe

while循環剛開始時死掉,它讀取2次並完全停止。

任何人都可以解釋,爲什麼?

+1

嘗試'fout.flush()' – rocketboy

回答

2

此代碼只爲我工作得很好。下面的代碼下載文件並寫入磁盤。

  URL url = new URL("http://nmap.org/dist/nmap-6.40-setup.exe"); 
    url.openConnection(); 
    byte data[] = new byte[16384]; 
    BufferedInputStream in = null; 
    in = new BufferedInputStream(url.openStream()); 
    int count = 0; 
    OutputStream fout = new FileOutputStream("C:/test.exe"); 
    while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read 
    { 
     fout.write(data, 0, count); // write the data to the file 
     long time = System.nanoTime(); 
     System.out.println(time); 
    } 
    fout.flush(); 
    fout.close(); 

我看到的只有一個可能的故障是,如果輸出流沒有正確關閉。該文件可能不會被刷新到磁盤中。

+0

感謝回答,我發現,問題出在我的校內網,apparantly我的應用程序並不想用它來工作。也許這是端口號,是否可以更改我用來下載文件的端口? – user2519193

+0

您無法更改端口。服務器將不得不要求客戶更改端口,請注意客戶端 – Prem

0
  URL url = new URL(logoPath); 
      in = new BufferedInputStream(url.openStream()); 
      while (true) { 

       if (in.available() == Integer.parseInt(app.getCoversize())) 
        break; 
      } 

file size = app.getCoversize();

+0

確定的時間間隔= getInterval() 文件大小= app.getLogosize() –

相關問題