java - 文件从未完全下载

标签 java android http file download

我正在尝试下载/恢复文件。恢复似乎有效,但整个下载带来了问题。执行此代码后,测试文件为 5242845。但应该是5242880!我在十六进制编辑器中打开了这两个文件,发现测试文件末尾缺少一些字节(开头没问题)。这是代码:

                String url = "http://download.thinkbroadband.com/5MB.zip";

                String DESTINATION_PATH = "/sdcard/testfile";

                URLConnection connection;

                connection = (HttpURLConnection) url.openConnection();

                File file = new File(DESTINATION_PATH);

                if (file.exists()) {
                    downloaded = (int) file.length();
                    connection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
                }
                connection.setDoInput(true);
                connection.setDoOutput(true);

                BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
                FileOutputStream fos = (downloaded == 0) ? new FileOutputStream(DESTINATION_PATH) : new FileOutputStream(DESTINATION_PATH, true);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                int x = 0;
                int i = 0;
                int lenghtOfFile = connection.getContentLength();

                while ((x = in.read(data, 0, 1024)) != -1) {
                    i++;
                    bout.write(data, 0, x);
                    downloaded += x;
         }

我认为问题出在这里 while ((x = in.read(data, 0, 1024)) != -1) {

例如我们有 1030 字节长的文件。第一次写入很好,bout.write(data,0,1024); 但是下一次 while ((x = in.read(data, 0, 1024)) != -1) { 得到 -1,因为还剩 1030-1024=6 个字节。我们正在尝试写入 1024 个字节!我知道不应该这样,但好像我是这么说的。我怎么知道这个?谢谢。

最佳答案

bout.flush();

和/或

bout.close();

关于java - 文件从未完全下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442274/

相关文章:

java - 散列 MAC 地址 Java/Android

java - 如何得到如下格式化输出?

android - 获取安卓应用的启动器Activity名称

node.js - 如何从 Node.js/Express 中的请求中检索实体主体(用于 CSP 违规报告)?

ios - 如何让 NSURLSession 从服务器返回 Content-Length(http header )。 Objective-C、iOS

java - 如何在java中获取更新的行ID

java - 通知方法如何工作

android - ConstraintLayout 不包装多行 EditText

Android Studio 图像分辨率

java - retrofit2 在 onFailure() 中获取 responseBody