Java-multi-thread download

Source: Internet
Author: User
Package COM. jwzhangjie;/*** Note: * Calculation Method of the download location of each thread: * start position: * (thread ID-1) * size of each piece * end position: * (thread ID * size of each thread)-1 * --- Note that the end position of the last thread is the end of the file. ** step: * 1. create a local temporary file with the same size as the Server File * 2. calculate the allocation of several threads to download resources on the server and know the location of the files downloaded by each thread * 3. start three threads, and each thread downloads the file at the corresponding position * 4. if all the threads download their own data, the resources on the server will be downloaded to the local */import Java. io. inputstream; import Java. io. randomaccessfile; import java.net. httpurlconnection; import java.net. URL; Pub LIC class demo {public static string Path = "http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe"; public static int threadcount = 3; public static void main (string [] ARGs) throws exception {// 1. connect to the server, get a file, get the file length, and create a local temporary file with the same size as the server url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5000 ); Conn. setrequestmethod ("get"); int code = Conn. getresponsecode (); If (code = 200) {// The length of the data returned by the server, in fact, is the object length int length = Conn. getcontentlength (); system. out. println ("total file length:" + length); // a temporary file named randomaccessfile RAF = new randomaccessfile ("setup.exe ", "RWD"); // specify the length of the created file. setlength (length); RAF. close (); // assume three threads are used to download resources. // Average file size downloaded by each thread. int blocksize = length/threadcount; For (INT threadid = 1; threadid <= threadcount; threadid ++) {// start position of the first thread download: int startindex = (threadid-1) * blocksize; int endindex = threadid * blocksize-1; if (threadid = threadcount) {// The download length of the last thread must be slightly longer. endindex = length;} system. out. println ("thread:" + threadid + "Download: ---" + startindex + "--->" + endindex); New downloadthread (path, threadid, startindex, en Dindex). Start () ;}} else {system. Out. printf ("server error! ") ;}}/*** Download file sub-thread each thread downloads the file * @ author Jie **/public static class downloadthread extends thread {private int threadid; private int startindex; private int endindex; /*** @ Param path: Path of the downloaded file to the server * @ Param threadid thread ID * @ Param startindex start position of the thread download * @ Param endindex end position of the thread download */ public downloadthread (string path, int threadid, int startindex, int endindex) {super (); this. threadid = threadid; this. st Artindex = startindex; this. endindex = endindex ;}@ overridepublic void run () {try {URL url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5000); Conn. setrequestmethod ("get"); // important: Requests the server to download some files and specify the position of the file Conn. setrequestproperty ("range", "bytes =" + startindex + "-" + endindex ); // The slave server requests all resources and returns 200 OK. If the slave server requests some resources, the system returns 206 okint code = Conn. getresponsecode (); Response E M. out. println ("Code:" + code); inputstream is = Conn. getinputstream (); // The request location has been set. The returned result is the input stream randomaccessfile RAF = new randomaccessfile ("setup.exe", "RWD") of the file corresponding to the current location "); // The position where the random write operation starts to write the RAF file. seek (startindex); // locate the file int Len = 0; byte [] buffer = new byte [1024]; while (LEN = is. read (buffer ))! =-1) {Raf. write (buffer, 0, Len);} is. close (); RAF. close (); system. out. println ("thread:" + threadid + "download completed");} catch (exception e) {e. printstacktrace ();}}}}

Add the source code to a Java project. For actual download, I will replace my own server with a valid link on the network for testing. The printed information is as follows:

 
Total file length: 5577744 threads: 1 download: --- 0 ---> 1859247 threads: 2 download: --- 1859248 ---> 3718495 threads: 3 download: --- 3718496 ---> 5577744 code: 206 code: 206 code: 206 thread: 2 download completed thread: 1 download completed thread: 3 download completed

In the future, I will encapsulate an interface. In fact, the principle of downloading software such as thunder is the same. Every server has bandwidth restrictions on download requests, therefore, downloading multiple threads increases the download bandwidth. However, the thread to be started is not limited. This is limited by your actual physical bandwidth.

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.