Resuming a HTTP download in Java

Let’s say you’re downloading a large file using Java, like so:

File file = new File("/downloads/some.file.ext");
URL url = new URL("http://some.url/some.file.ext");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
//...any other httpUrlConnection setup, such as setting headers
BufferedInputStream in = new BufferedInputStream(httpUrlConnection.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
try
{
    byte[] data = new byte[1024];
    int x = 0;
    while ((x = in.read(data, 0, 1024)) >= 0) 
    {
    	bout.write(data, 0, x);
    }
}
catch(Exception e)
{
	throw e;
}
finally
{
	if(bout!=null)
	{
		bout.flush();
		bout.close();
	}
	if(fos!=null)
	{
		fos.flush();
		fos.close();
	}
}

Now let’s say the file already exists locally and you need to resume it. Assuming the HTTP server on the other end supports file resume using the HTTP Range header, you can simply do the following:

//Add this right after you initialize httpUrlConnection but before beginning download
if(file.exists())
	httpUrlConnection.setRequestProperty("Range", "bytes="+file.length()+"-");

//And then you'd initialize the file output stream like so:
if(file.exists())
	fos = new FileOutputStream(file, true); //resume download, append to existing file
else
	fos = new FileOutputStream(file);

And that’s it! The Range header you we set for httpUrlConnection does the magic.

Leave a Reply

Your email address will not be published. Required fields are marked *