在下载大文件时,while循环挂在read(buffer)上 [英] while loop hangs at read(buffer) during downloading a large file

查看:57
本文介绍了在下载大文件时,while循环挂在read(buffer)上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用异步任务下载40Mb的mp3文件,下面是doInBackground部分的代码段.
实际发生的情况是下载开始正常,但是在随机的时间段后,while循环挂在i.read(buffer)上,没有异常. . . .请让我知道可能的解决方法

I am downloading a 40Mb mp3 file using asynchronous task, below is the code snippet of the doInBackground section.
What actually happening is that the download starts fine but after a random time period the while loop hangs at i.read(buffer), no exception is there . . . . please let me know the possible solution

try{

            url = new URL(addr);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();
            i = connection.getInputStream();
            f = new FileOutputStream(file);
            size = connection.getContentLength();

            while( i.available()>0 && (len = i.read(buffer))!=-1)
            {
                len = i.read(buffer);
                f.write(buffer, 0, len);
                d = d+len;
                mesg = handler.obtainMessage(1, "Size:"+size+" "+d);
                handler.sendMessage(mesg);
            }

            connection.disconnect();
            f.close();
            i.close();
            }
            catch(IOException e){e.printStackTrace();}
            catch(Exception e){e.printStackTrace();}
        }

推荐答案

只是发现一个非常大的错误:您两次调用i.read(buffer),一次是在检查条件时,然后是在正文中您的循环.

我可以指出您的代码中可能引起问题的几件事.我不会使用i.available(). available()方法对不同类型的流的工作方式有所不同.在这里,如果使用http通讯,我看不到使用它的任何意义,但是根据其功能(我还没有阅读文档),它可能会给您带来麻烦-因此,请忽略您的代码.另一件事是,您应该仅从输入流中读取内容长度所指示的字节数,因为连接发送完响应的全部内容后,另一端的服务器可能不会关闭该连接,因此可以您的while循环挂断的原因.巧合的是,我昨天回答了一个问题类似的问题,请阅读其他答案以获取更多说明: ^ ]
just spot a very big mistake: you call i.read(buffer) twice, once when you check the condition and then in the body of your loop.

I can point out a few things in your code that might cause problems. I wouldn''t use i.available(). the available() method works differently for different kind of streams. Here in case of http communication I dont see any point of using it, but depending on its functionality (I havent read the docs) it might cause problems for you - so leave that out of your code. Another thing is that you should read out only the number of bytes from your inputstream that is indicated by the content length because the connection might not be closed by the server on the other side after it sends the whole content of the response, this can be a reason for your while loop to hang up. Its a coincidence that I yesterday answered a question where the problem was similar, plz read the other answer for more explanation: Very Slow Winsock2 recv[^]


这篇关于在下载大文件时,while循环挂在read(buffer)上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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