开发者

android downloading progress

i'm writing a function to download file:

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 = c开发者_如何学编程onn.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();

my question is , how do i know the total byte of the file i'm downloading??

because , i wanna display the downloading progress. could someone teach me


Most times when downloading a file from a web server (over HTTP, such is your case) you'll have a response header named "Content-length". This will be the bytes in the response (a zip/exe/tar.gz or what not).

You'll maybe want to also read up about the HTTP HEAD request method. You can use this preemptively to find the value of the header. This is handy if you'd like to present a dialog to the user with the size of the file and give them the option to choose if they'd still like to download.

Check out the HTTP RFC for A LOT more information on the header and HEAD method.;

Using the command line tool Curl, you can easily get this header information for a file:

@>>> 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

Now to do this using the built in Java HttpUrlConnection you'll want to do something like:

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();
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜