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

查看:34
本文介绍了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 故障:你没有指望阅读() 总是 允许返回比您要求的更少的字节.因此,您的读取可能会少于 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 上 3G 的更高延迟网络或更小的数据包大小可能会加剧这种影响?

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

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

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