views:

7352

answers:

4

Hello,
I am having problems downloading a binary file (video) in my app from the internet. In Quicktime, If I download it directly it works fine but through my app somehow it get's messed up (even though they look exactly the same in a text editor). Here is a example:

    URL u = new URL("http://www.path.to/a.mp4?video");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4"));


    InputStream in = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ( (len1 = in.read(buffer)) > 0 ) {
         f.write(buffer);
    }
    f.close();
+5  A: 

One problem is your reading of the buffer. If every read of the input stream is not an exact multiple of 1024 you will copy bad data. Use:

byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) != -1 ) {
  f.write(buffer,0, len1);
}
Clint
On line 4, do you mean len1, not len?
Isaac Waller
I look at Ry4an example and assume you mean len1 - thanks.
Isaac Waller
+19  A: 

I don't know if it's the only problem, but you've got a classic Java glitch in there: You're not counting on the fact that read() is always allowed to return fewer bytes than you ask for. Thus, your read could get less than 1024 bytes but your write always writes out exactly 1024 bytes possibly including bytes from the previous loop iteration.

Correct with:

 while ( (len1 = in.read(buffer)) > 0 ) {
         f.write(buffer,0, len1);
 }

Perhaps the higher latency networking or smaller packet sizes of 3G on Android are exacerbating the effect?

Ry4an
What a stupid mistake... thanks! This is what happens when you don't read the tutorial properly :)
Isaac Waller
Thanks... helped me too.
fiXedd
+2  A: 

Don't forget to close the input stream (i.e. add in.close() to the above code).

A: 

Downloading is successfully getting done, but the respective downloaded file is not getting played on device media player.

Error while starting to play the music, "Media format is not supported..."

Please help....

Bilal Ahamad