【问题标题】:Incomplete file downloaded in android using DataInputStream使用 DataInputStream 在 android 中下载的不完整文件
【发布时间】:2014-11-24 14:22:50
【问题描述】:

我在服务器上有一个大约 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];

【问题讨论】:

    标签: android file android-asynctask download datainputstream


    【解决方案1】:

    我不确定,但尝试使用该条件

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多