Implementation of Java's multi-threaded breakpoint Download

Source: Internet
Author: User
Tags rar

Randomaccessfile class:
Instances of this class support reading and writing of random access files. The behavior of random access files is similar to a large byte array stored in the file system.

There is a pointer to the suppressed array. A cursor or index, called a file pointer. The input operation starts from the file pointer to read bytes. and moves the file pointer forward as it reads the bytes.

Assuming that the random access file is created in read/write mode, the output operation is also available. The output operation starts writing bytes from the file pointer. and moves the file pointer forward as it writes to the byte. Writing an output operation after the current end of the suppressed array causes the array to expand. The file pointer can be read by the Getfilepointer method. and set by the Seek method.

The following is a randomaccessfile implementation of Android under the breakpoint download demo.


The server side can simulate with Tomcat. Put the downloaded test file into the Webapp/root folder.
Let's start with the multithreaded download code that Java implements with the HttpURLConnection class:

 Public  class multithread {    Private Static intThreadCount =3;Private Static LongBlockSize;Private Static intRunningthreadcount; Public Static void Main(string[] args)throwsException {String Path ="Http://10.0.67.172/test.exe"; URL url =NewURL (path);        HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout ( the);//Timeout period        intCode = Conn.getresponsecode (); SYSTEM.OUT.PRINTLN (code);if(Code/ -==2){intSize = Conn.getcontentlength ();//Get the length of the resource fileSystem.out.println ("Request Resource size:"+ size); BlockSize = Size/threadcount;//How many blocks of the resource file are divided. Not a piece of sizeRunningthreadcount = ThreadCount;LongStartIndex =0;LongEndIndex =0;//Open several sub-threads to achieve multi-threaded download             for(inti =0; i < ThreadCount;                i++) {StartIndex = i * blockSize; EndIndex = (i +1) * BlockSize-1;if(i = = threadcount-1) {EndIndex = size-1; } System.out.println ("Open thread:"+ i +";"+"Start position:"+ StartIndex +":"+"End Position:"+ EndIndex);NewDownthread (Path, StartIndex, EndIndex, i). Start (); }        }    }Private Static  class downthread extends Thread{        PrivateString path;Private LongStartIndex;Private LongEndIndex;Private intThreadId; Public Downthread(String Path,LongStartIndex,LongEndIndex,intTHREADID) {Super(); This. Path = path; This. StartIndex = StartIndex; This. EndIndex = EndIndex; This. threadId = ThreadId; }@Override         Public void Run() {Try{URL url =NewURL (path);                HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout ( the); Conn.setrequestproperty ("Range","bytes="+ StartIndex +"-"+ EndIndex);//Set the read location of files on the server                intCode = Conn.getresponsecode ();if(Code/ -==2) {InputStream is = Conn.getinputstream (); File File =NewFile ("Temp.exe"); Randomaccessfile RAF =NewRandomaccessfile (file,"RW");                    Raf.seek (StartIndex); System.out.println ("section"+ ThreadId +"Start location of files:"+ string.valueof (startIndex));intLen =0;byte[] buffer =New byte[1024x768]; while(len = is.read (buffer))! =-1) {raf.write (buffer,0, Len);//write file} raf.close (); }            }Catch(Exception e)            {E.printstacktrace (); }        }    }}

The principle of a breakpoint download is to save the location of the last file download as a temporary file, and then delete it when the download is completely complete.

 Public  class multithread {    Private Static intThreadCount =3;Private Static LongBlockSize;Private Static intRunningthreadcount; Public Static void Main(string[] args)throwsException {String Path ="Http://10.0.67.172/test.rar"; URL url =NewURL (path);        HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout ( the);//Timeout period        intCode = Conn.getresponsecode (); SYSTEM.OUT.PRINTLN (code);if(Code/ -==2){intSize = Conn.getcontentlength ();//Get the length of the resource fileSystem.out.println ("Request Resource size:"+ size); BlockSize = Size/threadcount;//How many blocks are the resource file divided into, not a piece of sizeRunningthreadcount = ThreadCount;LongStartIndex =0;LongEndIndex =0; for(inti =0; i < ThreadCount;                i++) {StartIndex = i * blockSize; EndIndex = (i +1) * BlockSize-1;if(i = = threadcount-1) {EndIndex = size-1; } System.out.println ("Open thread:"+ i +";"+"Start position:"+ StartIndex +":"+"End Position:"+ EndIndex);NewDownthread (Path, StartIndex, EndIndex, i). Start (); }        }    }Private Static  class downthread extends Thread{        PrivateString path;Private LongStartIndex;Private LongEndIndex;Private intThreadId; Public Downthread(String Path,LongStartIndex,LongEndIndex,intTHREADID) {Super(); This. Path = path; This. StartIndex = StartIndex; This. EndIndex = EndIndex; This. threadId = ThreadId; }@Override         Public void Run() {intTotal =0;Try{File Positionfile =NewFile (ThreadId +". txt"); URL url =NewURL (path);                HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET");//Continue downloading the last file                if(Positionfile.exists () && positionfile.length () >0) {FileInputStream FIS =NewFileInputStream (Positionfile); BufferedReader reader =NewBufferedReader (NewInputStreamReader (FIS));//Gets the total size of the last download of the current threadString lasttotalstr = Reader.readline ();intLasttotal = integer.valueof (LASTTOTALSTR); System.out.println ("Total size of last thread download:"+ lasttotal);                    StartIndex + = Lasttotal;                    Total + = Lasttotal;                Fis.close (); } conn.setreadtimeout ( the); Conn.setrequestproperty ("Range","bytes="+ StartIndex +"-"+ EndIndex);//Set the read location of files on the server                intCode = Conn.getresponsecode ();if(Code/ -==2) {InputStream is = Conn.getinputstream (); File File =NewFile ("Temp.rar"); Randomaccessfile RAF =NewRandomaccessfile (file,"RW");                    Raf.seek (StartIndex); System.out.println ("section"+ ThreadId +"Start location of files:"+ string.valueof (startIndex));intLen =0;byte[] buffer =New byte[1024x768]; while(len = is.read (buffer))! =-1) {Randomaccessfile RF =NewRandomaccessfile (Positionfile,"RWD"); Raf.write (Buffer,0, Len);//write fileTotal + = Len;                        Rf.write (string.valueof (total) getBytes ());                    Rf.close ();                    } is.close ();                Raf.close (); }            }Catch(Exception e)            {E.printstacktrace (); }finally{synchronized(Downthread.class) {System.out.println ("Threads"+ ThreadId +"Finished downloading"); runningthreadcount--;if(Runningthreadcount <1) {System.out.println ("All the threads are working. Delete files that are temporarily logged "); for(inti =0; i < ThreadCount; i++) {File F =NewFile (i +". txt");                        System.out.println (F.delete ()); }                    }                }            }        }    }}

Execution Result:

Implementation of Java's multi-threaded breakpoint Download

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.