PackageCn.itcast.download;ImportJava.io.File;ImportJava.io.InputStream;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classMulthreaddownloader { Public Static voidMain (string[] args)throwsException {String path= "Http://i1.itc.cn/20140715/340a_ae147e1e_c21f_cc5d_afe0_a08407c77f1b_1.jpg"; intThreadsize = 3; Newmulthreaddownloader (). Download (path, threadsize); } Private voidDownload (String path,intThreadsize)throwsException {URL Downpath=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) downpath.openconnection (); Conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); if(Conn.getresponsecode () = = 200){ intLength = Conn.getcontentlength ();//get the length of a network fileFile File =NewFile (GetFileName (path)); Randomaccessfile Accessfile=NewRandomaccessfile (file, "RWD");//Generate local fileaccessfile.setlength (length); Accessfile.close (); //calculate the amount of data each thread is responsible for downloading intblock = length% Threadsize = = 0? Length/threadsize:length/threadsize +1; for(intThreadID = 0; ThreadID < threadsize; threadid++){ NewDownloadthread (ThreadID, Downpath, block, file). Start (); } } } //responsible for download operation Private Final classDownloadthreadextendsthread{Private intThreadID; PrivateURL Downpath; Private intBlock; Privatefile file; PublicDownloadthread (intThreadID, URL Downpath,intblock, File file) { This. ThreadID =ThreadID; This. Downpath =Downpath; This. block =Block; This. File =file; } Public voidrun () {intStartPosition = ThreadID * block;//where to start downloading data from a network file intEndposition = (threadid+1) * BLOCK-1;//where to end the download to the network file//indicates that the thread will download from the StartPosition location of the network file and download to the Endposition location end//range:bytes=startposition-endposition Try{randomaccessfile Accessfile=NewRandomaccessfile (file, "RWD"); Accessfile.seek (startposition);//move the pointer to a location in the fileHttpURLConnection conn =(HttpURLConnection) downpath.openconnection (); Conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Range", "bytes=" + startposition+ "-" +endposition); InputStream instream=Conn.getinputstream (); byte[] buffer =New byte[1024]; intLen = 0; while(len = instream.read (buffer))! =-1) {accessfile.write (buffer,0, Len); } accessfile.close (); Instream.close (); System.out.println ("First" + (threadid+1) + "Thread Download Complete"); }Catch(Exception e) {e.printstacktrace (); } } } /*** Get file name *@parampath Download Paths *@return */ Private Staticstring GetFileName (string path) {returnPath.substring (Path.lastindexof ("/") + 1); }}
Java Multi-Threaded download