使用 nio 模式恢复中断的下载

Resume an interrupted download using nio pattern

我已经搜索了很多次我的问题的答案,但都没有找到...那么我就在这里,我希望有人能帮助我!

我的代码在这里:

URLConnection connection = new URL("http://foo.bar/bar.b").openConnection();
File file = new File(connection.getURL().getPath().substring(1));

FileChannel download = new FileOutputStream(file).getChannel();

long totalBytes = connection.getContentLengthLong(), start = System.nanoTime(),
        time = System.nanoTime(), between, length, elapsed, data = 0;
int percent, totalPercent;

ReadableByteChannel channel = Channels.newChannel(connection.getInputStream());

while(download.transferFrom(channel, file.length(), 1024) > 0) {
    between = System.nanoTime() - time;

    if(between < 1000000000) continue;

    length = file.length();
    elapsed = System.nanoTime() - start;

    percent = (int) ((double) ((double)length / ((double)totalBytes == 0.0 ? 1.0 : (double)totalBytes) * 100.0));
    totalPercent = (int) (((double)downloaded / (double)releases.getUpdateLength()) * 100.0);

    manager.getForm().updateCurrentPercentage(
            percent,
            increment,
            files.size());

    manager.getForm().updateTotalPercentage(totalPercent,
            FileUtils.getTimeAsString(((elapsed * totalBytes / length) - elapsed)/1000000),
            FileUtils.getReadableSize(length - data));

    time = System.nanoTime();
    data = length;
}

当前代码可以完美运行和下载,但是当我中断应用程序并重新启动它时(例如,当下载为 56% 时),文件从 0..

重新启动

所以我正在测试调试,我发现

FileChannel download = new FileOutputStream(file).getChannel();

此行删除了我的本地文件(被中断)的内容,其长度从 0 重新开始。为什么?

我想知道我是否必须将 Http 属性与该方法一起使用。试了很多方法都没用..

好的,我只需要添加这一行:

if(file.exists())
    connection.setRequestProperty("Range", "bytes=" + file.length() + "-");

并将当前构造函数 FileOutputStream 替换为

FileChannel download = new FileOutputStream(file, file.exists()).getChannel();

有效:)