使用DataInputStream在android中下载不完整的文件

时间:2014-11-24 14:22:50

标签: android file android-asynctask download datainputstream

我在服务器上有一个大约90 MB的大文件及其.mp3文件我在android中使用此代码下载它

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            int contentLength = conexion.getContentLength();
            InputStream is = url.openStream();
            DataInputStream dis = new DataInputStream(is);
            byte[] buffer = new byte[1024];
            int length;
            FileOutputStream fos = new FileOutputStream(new File(
                    Environment.getExternalStorageDirectory() + "/"
                            + aurl[1]));
            long total = 0;
            while ((length = dis.read(buffer)) > 0) {
                total += length;
                publishProgress("" + (int) ((total * 100) / contentLength));
                fos.write(buffer, 0, length);
            }
            is.close();
            fos.close();
            dis.close();

但问题实际上是大部分时间它跳过内容而不下载完整文件并调用postexecute。 我希望您得到一些有用的建议,如何确保下载完整的文件并显示下载进度条,直到下载完整的内容。

如果我们使用字节数组大小从1024增加到它的某个倍数,那也很重要吗?

 byte data[] = new byte[4096];

1 个答案:

答案 0 :(得分:0)

我当然不知道但是尝试使用那个条件

while ((length = dis.read(buffer)) != -1) { }

我们读取0个字节的时刻可能会有,但这并不意味着它是流的结尾