如何使用 RandomAccessFile 恢复中断下载?

How to resume a interrupt download with RandomAccessFile?

我想用 RandomAccessFile 中断下载。这是代码

HttpGet httpget = HttpUtil.buildGet(URL)
httpget.setHeader("RANGE", "bytes=" + (position) + "-");
CloseableHttpResponse response = HttpClients.createDefault().execute(httpget) 
HttpEntity entity = response.getEntity();

int totalLen = 0;
InputStream is = entity.getContent();
RandomAccessFile writeFile = new RandomAccessFile(desc, "rw");
writeFile.seek(position);
byte[] buf = new byte[65536];
totalLen = 0;
int len = is.read(buf);
while (len > 0) {
   totalLen += len;
   writeFile.write(buf);
   len = is.read(buf);
}
response.close();
is.close();
writeFile.close();

HttpRequest return 206 并且下载成功完成,但是我得到一个错误的文件,该文件比源文件大很多,我无法打开它。 这段代码有什么问题?如何使用 RandomAccessFile 恢复中断下载?

来自 :

Accept-Ranges: bytes
ETag: W/"243174107-1583744547157"
Last-Modified: Mon, 09 Mar 2020 09:02:27 GMT
Content-Range: bytes 32243658-243174106/243174107
Content-Type: application/zip
Content-Length: 210930449

请求指定了 32,243,658 的起始位置,并下载了剩余的 210,930,449 字节,最后得到一个 243,174,107 字节的文件。

嗯,不,它最终得到一个文件 至少 243,204,042 字节,即 29,935 字节太多,因为代码总是写已满 buffer,即使缓冲区未完整读取。

文件很可能比那个大很多,因为数据是以较小的块通过网络传输的,所以很可能缓冲区没有充满 65,536 字节read() 电话。

read() returns len 值是有原因的。您的代码应该是:

writeFile.write(buf, 0, len);

此外,您应该使用 try-with-resources,内联 read() 调用很常见,因此不会重复,例如代码应该是:

int totalLen = 0;
try (RandomAccessFile writeFile = new RandomAccessFile(desc, "rw")) {
    writeFile.seek(position); // should use value from response header here, not requested value
    try (InputStream is = entity.getContent()) {
        byte[] buf = new byte[65536];
        for (int len; (len = is.read(buf)) > 0; ) {
            totalLen += len;
            writeFile.write(buf, 0, len);
        }
    }
}
response.close();