Implementation of Java's multi-threaded breakpoint Download

Source: Internet
Author: User
Tags rar

Randomaccessfile class:
Instances of this class support read and write to random-access files. Random access to a file behaves like a large byte array stored in the file system. There is a pointer to the implied array, a cursor or an index, called a file, and the input operation reads the bytes from the file pointer, and moves the file pointer forward as the byte is read. If the random Access file is created in read/write mode, the output operation is also available, and 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 through the Seek method.

Below is a randomaccessfile implementation of Android under the breakpoint download demo.
The server side can be simulated with Tomcat, the downloaded test files will be placed in the Webapp/root directory.
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 are the resource file divided into, 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 location:"+ 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 full download is 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 location:"+ 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 +"Download complete."); runningthreadcount--;if(Runningthreadcount <1) {System.out.println ("All the threads have finished working." Delete files for temporary records "); for(inti =0; i < ThreadCount; i++) {File F =NewFile (i +". txt");                        System.out.println (F.delete ()); }                    }                }            }        }    }}

Operation Result:

Implementation of Java's multi-threaded breakpoint 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.