Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用nio模式恢复中断的下载_Java_Http_Download_Nio_Resume - Fatal编程技术网

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

Java 使用nio模式恢复中断的下载,java,http,download,nio,resume,Java,Http,Download,Nio,Resume,我已经搜索了我的问题的答案很多次没有找到任何一个。。。然后我在这里,我希望有人能帮助我 我的代码在这里: URLConnection connection = new URL("http://foo.bar/bar.b").openConnection(); File file = new File(connection.getURL().getPath().substring(1)); FileChannel download = new FileOutputStream(file).get

我已经搜索了我的问题的答案很多次没有找到任何一个。。。然后我在这里,我希望有人能帮助我

我的代码在这里:

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;
}
此行将删除我的本地文件的内容(该文件已中断)&其长度将在0处重新启动。为什么?


我想知道是否必须将Http属性用于该方法。我尝试了很多方法,但似乎都不管用。

好的,我只是添加了这一行:

if(file.exists())
    connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
并将当前构造函数FileOutputStream替换为

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

它可以工作:)

好的,我发现了问题的一部分。我必须将FileOutputStream与这个构造函数一起使用:public FileOutputStream(File File,boolean append)并将append设置为true
FileChannel download = new FileOutputStream(file, file.exists()).getChannel();