Java Multi-Threaded download

Source: Internet
Author: User

 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

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.