Skip to main content

Android download binary file problems






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




Comments

  1. 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?

    ReplyDelete
  2. 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);
    }

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

    ReplyDelete
  4. public class download extends Activity {

    private static String fileName = "sawan123.3gp";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try {
    URL url = new URL("http://joomlavogue.in/staff/sawanmodi/sawan.3gp");
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();

    String PATH = Environment.getExternalStorageDirectory()
    + "/download/";
    Log.v("log_tag", "PATH: " + PATH);
    File file = new File(PATH);
    file.mkdirs();
    File outputFile = new File(file, fileName);
    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ((len1 = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len1);
    }
    fos.close();
    is.close();
    } catch (IOException e) {
    Log.d("log_tag", "Error: " + e);
    }
    Log.v("log_tag", "Check: ");
    } }

    ReplyDelete
  5. Just use apache's copy method (Apache Commons IO) - the advantage of using Java!

    IOUtils.copy(is, os);


    Do not forget to close the streams in a finally block:

    try{
    ...
    } finally {
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    }

    ReplyDelete
  6. I fixed the code based on previous feedbacks on this thread. I tested using eclipse and multiple large files. It is working fine. Just have to copy and paste this to your environment and change the http path and the location which you would like the file to be downloaded to.

    try {
    //this is the file you want to download from the remote server
    String path ="http://localhost:8080/somefile.zip";
    //this is the name of the local file you will create
    String targetFileName
    boolean eof = false;
    URL u = new URL(path);
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    FileOutputStream f = new FileOutputStream(new File("c:\\junk\\"+targetFileName));
    InputStream in = c.getInputStream();
    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ( (len1 = in.read(buffer)) > 0 ) {
    f.write(buffer,0, len1);
    }
    f.close();
    } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (ProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    Good luck
    Alireza Aghamohammadi

    ReplyDelete
  7. I like the new look of thehtml5 vedio player Player is faster is better and my slow computer with crappy video card will not got slow anymore, nice job you guys!

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.