Java-multi-thread breakpoint download

Source: Internet
Author: User

In the previous chapter, we implemented the multi-threaded download function. Here we add the breakpoint download function to prevent unexpected program exit during the download process. The Code is as follows:

 

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 data, the resources on the server will be downloaded to the local device. ** breakpoint download: * 1. use a file to record the download length of each thread * 2. before each download starts, read the file. If the file exists and has a length greater than 0, extract the length * 3. add the starting position of each thread + the downloaded length * 4. after downloading all threads, delete File */import Java. io. file; import Java. io. fileinputstream; import Java. io. inputstream; import Java. io. randomaccessfile; import java.net. httpurlconnection; import java.net. URL; public class demo {public static string Path = "http: // 192.168.5.103: 8080/examples/downloader.exe"; // "http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe"; public static int threadcou Nt = 3; public static int runningthread = 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. getcontentleng Th (); 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 {// check whether a file with a download length record exists. If yes, read the file tmp_file = new file (threadid + ". TXT "); If (tmp_file.exists () & tmp_file.length ()> 0) {fileinputstream FIO = new fileinputstream (tmp_file); byte [] temp = new byte [1024]; int Len = FIO. read (temp); string downloadlen = new string (temp, 0, Len); int downloadint = integer. parseint (downloadlen ); Startindex = downloadint; // modify the actual start position of the download system. out. println ("thread:" + threadid + "actual download location:" + startindex + "--->" + endindex); FIO. close () ;}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); // if the server requests all resources, the system returns 200 OK. If the server requests some resources, the system returns 2. 06 okint code = Conn. getresponsecode (); system. 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]; int Total = 0; // The length of the downloaded data while (LEN = is. read (buffer ))! =-1) {randomaccessfile file = new randomaccessfile (threadid + ". TXT "," RWD "); RAF. write (buffer, 0, Len); Total + = Len; file. write ("" + (total + startindex )). getbytes (); file. close ();} is. close (); RAF. close (); system. out. println ("thread:" + threadid + "download completed");} catch (exception e) {e. printstacktrace () ;}finally {runningthread --; If (runningthread = 0) {// All threads have been executed for (INT I = 1; I <= threadcount; I ++) {file = new File (I + ". txt"); file. Delete ();} system. Out. println ("all files have been downloaded! ");}}}}}

Test results:

First download:

Total file length: 5562040 threads: 1 download: --- 0 ---> 1854012 threads: 2 download: --- 1854013 ---> 3708025 threads: 3 download: --- 3708026 ---> 5562040 code: 206 code: 206 code: 206

Second download:

Total file length: 5562040 threads: 1 download: --- 0 ---> 1854012 threads: 2 download: --- 1854013 ---> 3708025 threads: 3 download: --- 3708026 ---> 5562040 threads: 1 Real download location: 21504 ---> 1854012 thread: 2 Real download location: 1871421 ---> 3708025 thread: 3 Real download location: 3726458 ---> 5562040 code: 206 code: 206 code: 206

Download completed:

Total file length: 5562040 threads: 1 download: --- 0 ---> 1854012 threads: 2 download: --- 1854013 ---> 3708025 threads: 3 download: --- 3708026 ---> 5562040 threads: 2 Real download location: 3512893 ---> 3708025 thread: 3 Real download location: 5268602 ---> 5562040 thread: 1 Real download location: 1677312 ---> 1854012 code: 206 code: 206 code: 206 thread: 1 download completed thread: 2 download completed thread: 3 download completed all files downloaded!

As follows:

 

The downloaded file can be used, indicating that the download is successful. The UI version of the download tool will be updated tomorrow.

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.