我已经多次搜索了我的问题的答案而没有找到任何人...然后我在这里,我希望有人能够帮助我!
我的代码在这里:
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;
}
目前的代码适用&amp;下载完美,但当我打断应用程序&amp;重新启动它(例如,当下载为56%时),文件从0开始重新启动。
所以我正在测试调试&amp;我找到了
FileChannel download = new FileOutputStream(file).getChannel();
此行删除我本地文件的内容(已被中断),&amp;它的长度重新开始为0.为什么?
我想知道我是否必须使用这些方法的Http属性。我尝试了很多方法,但似乎没什么用。
答案 0 :(得分:2)
好的,我只想添加这一行:
if(file.exists())
connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
并用
替换当前构造函数FileOutputStreamFileChannel download = new FileOutputStream(file, file.exists()).getChannel();
有效:)