JAVA multi-threaded download and breakpoint continuation

Source: Internet
Author: User

Breakpoint continuation and multi-threaded download principle is the same;

Key Code key location: Set breakpoints

Http2.setrequestproperty ("RANGE", "bytes=" +startl+ "-");//sets the breakpoint location to request from the server which byte of the file to start reading.
Osf.seek (STARTL);//Set the local file from which byte to start writing.

If it is single-threaded, the first to determine whether the download file already exists;
If there is a start breakpoint continuation, the method is the same as multithreading: Because the breakpoint is resumed from the last transmission interrupted byte start, the first to get the location of the last outage, both the file length (for single thread) F.length () and then set the HTTP request Header properties range, This property tells the server which itself to start reading files from.
Sets the local file to write the starting byte, and continues the write from the last transport breakpoint (the breakpoint resumes)

Osf.seek (offset)//The method is set to write a file starting from offset after one byte
Note: Multithreading cannot use file length as the starting byte of the write file, need to have the configuration file record the location of the last read and write, Thunderbolt download is both the use of this method.


Here is an example:

import java.io.inputstream;import java.io.randomaccessfile;import java.net.httpurlconnection; Import java.net.url;public class downloadthread extends thread {string urlt ;int startl;int end; string filename; Randomaccessfile osf;public downloadthread (int i, string url, string  Filename, int start, int end)  {this.setname ("T"  + i); //  Child thread Name this.urlt = url; // this.filename = filename;this.startl = start;  //  child thread read/write start byte this.end = end;//  child thread write end byte length}public void run ()  {try  {osf = new randomaccessfile (filename,  "RW"); Url url = new url (URLT); httpurlconnection http2 =  (HttpURLConnection)  url.openconnection (); Http2.setrequestproperty ("User-agent",  "Netfox"); Http2.setrequestproperty ("RANGE",  "bytes="  + startl +  "-");//  sets the breakpoint location to request from the server which byte of the file to start reading. Osf.seek (STARTL);//  sets the local file from which byte to start writing Inputstream input = http2.getinputstream (); byte b[ ] = new byte[1024];//  set buffer pool, read-only 1024 bytes each time int l;//  calculate the length of the file that the child thread reads and writes, Terminates thread int i;l = 0; when length is greater than average download length per child thread SYSTEM.OUT.PRINTLN ("Thread" +this.getname ()  +  ": Start Download ...");while  ((I = input.read (b, 0 ,  1024)  != -1 && l < end)  { //  Thread download byte length control error is less than buffer pool size, this example osf.write buffer pool 1024 bytes (b, 0, i);b = new byte[1024];//  re-assigns the value, Avoid re-reading into old content l += i;} SYSTEM.OUT.PRINTLN ("Thread" +this.getname ()  +  ": Download Complete ...");  catch  (exception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}
import java.io.file;import java.io.ioexception;import java.net.httpurlconnection;import  java.net.url;public class downloadfile {/** *  @param  args */static int  len;//  thread average download file length static int bn;//  the number of bytes per thread written to the file static int tn; //  Number of Threads static string urlt;// static string filename;public static void  Main (String[] args)  {// todo auto-generated method stubtry {urlt =   "Http://im.baidu.com/download/BaiduHi_4.2_Beta.exe";filename =  "c:\\" + urlt.split ("//") [1 ].split ("/") [Urlt.split ("//") [1].split ("/") .length - 1]; System.out.println ("FileName:" +filename); Url url = new url (URLT); httpurlconnection http =  (HttpURLConnection)  url.openconnection (); System.out.println ("FileSize:"  + http.getcontentlength ()) tn = 5;//here set 5 threads to download a file tn =  5;  judge average each thread needs to download the file length len = http.getcontentlength ()  / tn;//the remainder (the remainder is automatically shed) calculates the average length of each line thread executes download, The last thread, plus the remainder, is the length of the entire file, File f = new file (fileName);if  (f.exists ())  {f.delete ();} SYSTEM.OUT.PRINTLN ("Temp File Length:"  + f.length ()); thread t;//  Download Child thread,for  (int j = 0; j < tn; j++)  {if   (j == tn - 1)  {//  if the last thread adds a remainder length byte bn = len +  ( Http.getcontentlength ()  % tn);}  else {bn = len;} System.out.println ("T"  + j +  "thread download Length:"  + bn +  "Start byte:"  + len &NBSP;*&NBSP;J); T = new downloadthread (J, urlt, filename, len * j, &NBSP;BN); T.start ();}}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();}}}


This article is from the "OMA" blog, so be sure to keep this source http://oma1989.blog.51cto.com/1931488/1559627

JAVA multi-threaded download and breakpoint continuation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.