Android download binary file problems Android download binary file problems java java

Android download binary file problems


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?


new DefaultHttpClient().execute(new HttpGet("http://www.path.to/a.mp4?video"))        .getEntity().writeTo(                new FileOutputStream(new File(root,"Video.mp4")));


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