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

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

问题描述


我有下载的二进制文件(视频)在从互联网上我的应用程序的问题。在QuickTime,如果我直接下载它工作正常,但通过我的应用程序,不知何故,得到的搞砸了(尽管它们看起来很在文本编辑器相同)。这里有一个例子:

  URL U =新的URL(http://www.path.to/a.mp4?video);
    HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
    c.setRequestMethod(GET);
    c.setDoOutput(真正的);
    c.connect();
    FileOutputStream中F =新的FileOutputStream(新文件(根,Video.mp4));


    在的InputStream = c.getInputStream();

    byte []的缓冲区=新的字节[1024];
    INT LEN1 = 0;
    而((LEN1 = in.read(缓冲液))大于0){
         f.write(缓冲液);
    }
    f.close();
 

解决方案

我不知道这是否是唯一的问题,但你有一个经典的Java小故障在那里:你不能指望读的事实()是的总是的允许返回比你要求的字节数更少。因此,你的阅读可以得到小于1024字节,但是你写始终写出正是1024个字节可能包括从previous循环迭代字节。

纠正:

 ,而((LEN1 = in.read(缓冲))大于0){
         f.write(缓冲液,0,LEN1);
 }
 

也许,高延迟网络或3G Android上较小的数据包大小加剧的影响?


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

解决方案

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?

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

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