Multi-threaded breakpoint continuation of the demo

Source: Internet
Author: User

import java.io.bufferedreader;import java.io.file;import java.io.fileinputstream;import  java.io.inputstream;import java.io.inputstreamreader;import java.io.randomaccessfile;import  The principle of java.net.httpurlconnection;import java.net.url;/** *     multi-threaded breakpoint continuation transmission  * 1 , when the multi-threaded abrupt interruption, in the cache file to save the location of the interrupt,  * 2, when the continuation of the time, read the location in the cache file, and then as the beginning of the location to download.  *  @author  Sheamus * */public class MutilHttpDownload {     //the number of threads completed downloading     static int finishedThread = 0;     static String path =  "Http://10.31.2.6:8080/demo/QQ.exe";     static int processnum = 3;        public  static void main (String[] args)  {        // Request the size of the file and create a cache file of the same size         try {            url url =  new url (path);             // Create a QQ.exe file in the project directory             file file  = new file ("QQ.exe");             Randomaccessfile raf = new randomaccessfile (file,  "RWD");                          HttpURLConnection conn =  (HttpURLConnection)  url.openconnection ();             conn.setrequestmethod ("GET");             conn.setreadtimeout (;     )       &nbsP;conn.setreadtimeout (;             )            if (Conn.getresponsecode ()  == 200)  {                int  length = conn.getcontentlength ();                 //setting the size of the cache file                  raf.setlength (length);                 raf.close ();                 //calculate the size that each thread should download                  int size = length / PROCESSNUM;                 //calculates where each thread starts and ends                  for (int i = 0; i  < processnum; i++)  {                                          int startindex = i * size ;                     int endIndex =  (i + 1)  * size - 1;                     // At the time of the last thread, the last position was the total length minus 1              .     &nBsp; if (i ==  (processnum - 1))  {                         endIndex  = length - 1;                     }                     //start thread execution Download                      new singledownloadthread ( startindex,endindex,i). Start ();                 }            }                     }  catch  (EXCEPTION&NBsp;e)  {            // TODO  auto-generated catch block             E.printstacktrace ();        }    }}class  singledownloadthread extends thread {    private int startindex;     private int endIndex;    private int  Currentthreadid;    public singledownloadthread (int startindex, int  Endindex, int currentthreadid)  {        super ();         this.startIndex = startIndex;         this.endIndex = endIndex;         This.currentthreadid = currentthreadid;    }     @Override     public string  tostring ()  {        return  "downloadthread [ startindex= " + startIndex + ",  endindex= "                 + endIndex +  ",  currentthreadid="  + currentThreadId +  "]";    }     @Override      public void run ()  {        int  total = 0;        //Download the part of the thread to download          try {            // Define the cache file to save the downloaded location             file tempfile  = new file ("Temp"   + currentthreadid + ". txt");             if (tempfile.exists ())  {                 //download, if there is a cache file, read the cached file, replace this number with the starting position                  fileinputstream fis = new fileinputstream ( Tempfile);                 Bufferedreader bis = new bufferedreader (New inputstreamreader (FIS));                 int tempstartindex  = integer.parseint (Bis.readline ());                 startIndex = tempStartIndex;             &nBsp;   fis.close ();             }             system.out.println ("The download interval is  :"  + startindex + " -- > "  + endindex + "------------------------- -------");            file file =  New file ("QQ.exe");             Randomaccessfile raf = new randomaccessfile (file,  "RWD");                          url url = new url (Mutilhttpdownload.path);                          httpurlconnection conn = (httpurlconnection)  url.openconnection ();             conn.setrequestmethod ("GET");             conn.setconnecttimeout (;            ) Conn.setreadtimeout (            //); Set the section to download             conn.setrequestproperty ("Range",  "Bytes="  + startIndex +  "-"  + endindex);             //will randomly read a pointer to the stream that reads the file to the beginning of the file to be read              raf.seek (StartIndex);             //partial file Gets the successful return code is 206&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF (Conn.getresponsecode ()  ==  206)  {                 Inputstream in = conn.getinputstream ();                 byte[] b = new byte[1024];                 int len = 0;                 while (len  = in.read (b))  != -1)  {                     raf.write (B, 0, len);                     total  += len;                     systeM.out.println ("Threads  "  + currentThreadId +  "downloaded  "  + total);                     // Create an output stream write out where you are currently reading                      randomaccessfile tempraf = new randomaccessfile (TempFile,   "RWD");                     tempraf.write ((total+ ""). GetBytes ());                     tempraf.close ();                 }                 system.out.println ("Threads  "  +  currentthreadid + "Download done!");                 raf.close ();                                   mutilhttpdownload.finishedthread++;                 synchronized  (Mutilhttpdownload.path)  {                     if ( Mutilhttpdownload.finishedthread == mutilhttpdownload.processnum)  {                          for (int i = 0; i < mutilhttpdownload.processnum; i++)  {           &nbsP;                 file  f = new file ("Temp"  + i +  ". txt");                              system.out.println ("delete"  + f.getname ()  + "file");                              f.delete ();                         }                          //only let one thread come in and delete the file, otherwise it will be abnormal                          mutilhttpdownload.finishedthread = 0;                     }                 }             }                     } catch  (exception e)  {             // TODO Auto-generated  Catch block            e.printstacktrace ();         }                     }}


Multi-threaded breakpoint continuation of the demo

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.