Java Multi-threaded breakpoint Continuation download

Source: Internet
Author: User

The continuation of the breakpoint is the use of temporary files, at the time of downloading the download progress of each thread to a progress file, and so on the next download time directly from the progress file read this value, and then + on the beginning of the value to continue to download it

 PackageDown ;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classDown {Static intThreadCount = 3; //record the number of download threads completed    Static intFinishthread = 0; StaticString Path = "Http://192.168.21.1:8080/ok/TGPSetup.exe"; /**     * @paramargs*/     Public Static voidMain (string[] args) {Try{URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); if(Conn.getresponsecode () = = 200) {                //the length of the first request to download                intLength =conn.getcontentlength (); //The file name should be truncated from the stringFile File =NewFile ("TGPSetup.exe"); //generate temporary files before downloading, occupying a locationRandomaccessfile RDM =NewRandomaccessfile (file, "RWD"); //to the temporary file sizerdm.setlength (length); //CloseRdm.close (); //calculate the length that each thread should download                intSize = length/ThreadCount; //assign start and end locations for each thread                 for(inti = 0; i < ThreadCount; i++) {                    intstart = i *size; intEnd = (i + 1) * size-1; //the end position of the last thread is the total length                    if(i = = ThreadCount-1) {End=length; }                    //each time a new thread is called                    NewDownthread (Start, end, I). Start (); }            }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}//ThreadsclassDownthreadextendsThread {Private intstart; Private intend; Private intthreadId;  PublicDownthread (intStartintEndintthreadId) {         This. Start =start;  This. end =end;  This. ThreadId =threadId; } @Override Public voidrun () {Try {            //Create a progress fileFile Progressfile =NewFile (threadId + ". txt"); //Determine if there is a record of the progress of the file, if any, the start position is re-assigned value            if(Progressfile.exists ()) {FileInputStream fis=NewFileInputStream (Progressfile); BufferedReader BR=NewBufferedReader (NewInputStreamReader (FIS)); Start+=Integer.parseint (Br.readline ());            Fis.close (); } System.out.println (ThreadId+ "Thread download Interval" + start + "---" +end); //Request Network againURL url =NewURL (Down.path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); //set the length of the file for this requestConn.setrequestproperty ("Range", "bytes=" + Start + "-" +end); //request part of the data is 206            if(Conn.getresponsecode () = = 206) {                //the file input stream that gets the requested lengthInputStream is =Conn.getinputstream (); byte[] B =New byte[1024]; intLen = 0; //record the number of bytes downloaded each time                intTotle = 0; //The file name should be truncated from the stringFile File =NewFile ("TGPSetup.exe"); //the file that occupies the previous position, the equivalent of the output streamRandomaccessfile RDM =NewRandomaccessfile (file, "RWD"); //change the start position of the write fileRdm.seek (start);  while(len = Is.read (b))! =-1) {                    //every time the data in the stream is written to the temp file .Rdm.write (b, 0, Len); Totle+=Len; //System.out.println (threadId + "thread" + "downloaded" + totle); //Save the total number of downloads in a progress fileRandomaccessfile RDM1 =Newrandomaccessfile (Progressfile,"RWD"); Rdm1.write ((Totle+ ""). GetBytes ());                Rdm1.close ();                } rdm.close (); Down.finishthread++; //download End Delete progress file                if(down.finishthread==Down.threadcount) {                    //Plus sync lock                    synchronized(Down.path) { for(inti = 0; i < Down.threadcount; i++) {File F=NewFile (i+ ". txt");                        F.delete (); } down.finishthread= 0; }                }            }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Java Multi-threaded breakpoint Continuation download

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.