URL url = new URL("http://download.thinkbroadband.com/20MB.zip");
URLConnection connection = url.openConnection();
File fileThatExists = new File(path);
OutputStream output = new FileOutputStream(path, true);
connection.setRequestProperty("Range", "bytes=" + fileThatExists.length() + "-");
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0 , count);
}
in this code I try to resume download. Target file is 20MB. But when I stop download on 10mb, then contunue, I get file with filesize 30MB. It seems that it continue writing to file, but cant partly download from server. Wget -c works great with this file. How can I resume file download?
Check out this thread which has a problem similar to yours. If wget is working, then the server clearly supports resuming downloads. It looks like you're not setting the
If-Range
header as mentioned in the accepted answer of the above link. ie. add:I have a way for your code to work.
I guess the problem you are facing is calling
url.openStream()
afterurl.openConnection()
.url.openStream()
is equivalent tourl.openConnection().getInputStream()
. Hence, you are requesting the url twice. Particularly the second time, it is not specifying the range property. Therefore download always starts at the beginning.You should replace
url.openStream()
withconnection.getInputStream()
.This is not my code, but it works.
Since the question is tagged with Android: Have you tried using DownloadManager. It handles all this stuff nicely for you.
How about this?
Used
break;
to test the code.. ;)