Android下载二进制文件问题 [英] Android download binary file problems

查看:107
本文介绍了Android下载二进制文件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上的应用程序中下载二进制文件(视频)时遇到问题。在Quicktime中,如果我直接下载它,它可以正常工作,但通过我的应用程序,它会被弄乱(即使它们在文本编辑器中看起来完全相同)。这是一个例子:

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


推荐答案

我不知道这是唯一的问题,但是您在这里遇到了一个经典的Java故障:您不会指望read()始终允许返回比您要求的字节少的事实。因此,您的读取可能会少于1024字节,但是写入总是写出1024个字节,可能包括来自上一循环迭代的字节。

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.

正确使用:

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

也许Android的更高延迟网络或更小的数据包大小会加剧效果?

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

这篇关于Android下载二进制文件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆