2010-11-19 46 views
0

我正在寫一個函數來下載文件:Android的下載進度

URL _url = new URL("http://kevin95800.free.fr/Music/Jay%20Sean%20-%20Down%20(ft.%20Lil%20Wayne).mp3"); 
     URLConnection conn = _url.openConnection(); 
     conn.connect(); 

     InputStream is = conn.getInputStream(); 

     if(is == null) 
     { 
      throw new RuntimeException("stream is null"); 
     } 

     File musicFile = new File("/sdcard/music/" , "mitpig.mp3"); 

     FileOutputStream fos = new FileOutputStream(musicFile); 

     byte buf[] = new byte[128]; 

     do 
     { 
      int numread = is.read(buf); 
      Log.i("html2" , numread+" "); 
      if(numread <=0) 
       break; 

      fos.write(buf , 0 , numread); 

     }while(true); 

     is.close(); 

我的問題是,我怎麼知道我在下載文件的總字節?

因爲我想顯示下載進度。有人可以教我

回答

1

大多數時候,從Web服務器下載文件(通過HTTP,這是你的情況),你將有一個名爲「Content-length」的響應頭。這將是響應中的字節(zip/exe/tar.gz或不是)。

你也許還想讀一下HTTP HEAD請求方法。您可以搶先使用它來查找標題的值。如果您想以文件大小向用戶展示對話框並給他們選擇是否仍想下載的選項,這很方便。

檢查出the HTTP RFC瞭解更多有關標頭和HEAD方法的信息。

使用命令行工具捲曲,就可以輕鬆搞定這個頭信息的文件:

@>>> curl -I http://www.reverse.net/pub/apache//mahout/0.4/mahout-distribution-0.4-src.zip 
HTTP/1.1 200 OK 
Date: Fri, 19 Nov 2010 07:20:20 GMT 
Server: Apache 
Last-Modified: Thu, 28 Oct 2010 14:58:36 GMT 
ETag: "f550b5-4dc0af-938e1f00" 
Accept-Ranges: bytes 
Content-Length: 5095599 
Content-Type: application/zip 

我們做到這一點使用內置在Java中HttpURLConnection的,你會想要做的事,如:

import java.net.HttpURLConnection; 
import java.net.URL; 

public class Example { 
    public static void main(String[] args) 
    { 
    try { 
    HttpURLConnection con = 
     (HttpURLConnection) new URL("http://www.reverse.net/pub/apache"+ 
      "//mahout/0.4/mahout-distribution-0.4-src.zip").openConnection(); 
     con.setRequestMethod("HEAD"); 
     con.connect(); 
     int numbytes = Integer.parseInt(con.getHeaderField("Content-length")); 
     System.out.println(String.format(
      "%s bytes found, %s Mb", numbytes, numbytes/(1024f*1024))); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
}