Multi-threaded Breakpoint Download

Source: Internet
Author: User

connecting to the network via HttpURLConnection

create random Access files by Randomaccessfile, determine the size of blank files, and specify where to read and store

through the message header Range Set Breakpoints Download

Import Java.io.bufferedreader;import java.io.file;import Java.io.fileinputstream;import Java.io.InputStream;import Java.io.inputstreamreader;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.URL; public class Mutilethreaddownload {/** * number of threads */private static int threadcount = 3;/** * size of each download chunk */private static long blocksize;/** * Number of running threads */private static int runningthreadcount;/** * @param args * @throws Exception */public Static V OID Main (string[] args) throws Exception {//the path of the server file String path = "Http://192.168.1.100:8080/ff.exe"; URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); conn.setconnecttimeout, int code = Conn.getresponsecode (), if (code = =) {Long size = Conn.getcontentlength (); The size of the file returned to the service System.out.println ("Size of the server file:" + size); blocksize = size/threadcount;//1. First create a local blank file that is identical in size to the server. File File = new file ("Temp.exe"); Randomaccessfile RAF = new RandomaccessfilE (file, "RW"); Randomly accessed files, you can create a blank file that determines the size and can specify where to read and store raf.setlength (size);//2. Open several sub-threads to download the corresponding resources separately.  Runningthreadcount = threadcount;for (int i = 1; I <= threadcount; i++) {//http Protocol and Java are also starting from 0, and also begin valid and end invalid long StartIndex = (i-1) * Blocksize;long endIndex = i * blocksize-1;if (i = = ThreadCount) {//last thread endIndex = size-1;} SYSTEM.OUT.PRINTLN ("Open thread:" + i + "Download location:" + StartIndex + "~" + endIndex); new Downloadthread (Path, I, StartIndex, EndIndex). Start ();}} Conn.disconnect ();} private static class Downloadthread extends Thread {private int threadid;private long startindex;private long Endindex;pri Vate string path;public downloadthread (string path, int threadId, long startindex,long endIndex) {This.path = path;this.th Readid = Threadid;this.startindex = Startindex;this.endindex = EndIndex;} @Overridepublic void Run () {try {///when the total size of the front-thread Download int = 0; File Positionfile = new file (threadId + ". txt"); URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) Url.opencoNnection (); Conn.setrequestmethod ("GET");//Continue downloading data from the previous location if (positionfile.exists () && positionfile.length () > 0) {//To determine if there is a record fileinputstream FIS = new FileInputStream (positionfile); BufferedReader br = new BufferedReader (new InputStreamReader (FIS));//Gets the total size of the last download of the current thread is how much string lasttotalstr = Br.readline (); int lasttotal = integer.valueof (LASTTOTALSTR); System.out.println ("Last thread" + threadId + "Total size of Download:" + lasttotal); StartIndex + = lasttotal;total + = lasttotal;//plus the total size of the last download. Fis.close ();} Set the message header Conn.setrequestproperty ("Range", "bytes=" + StartIndex + "-" + EndIndex); Conn.setconnecttimeout (+); int code = Conn.getresponsecode ();  System.out.println ("code=" + code); Here the code is not 200 is the 206InputStream is = Conn.getinputstream (); File File = new file ("Temp.exe"); Randomaccessfile RAF = new Randomaccessfile (file, "RW");//Specify where the file begins to write. Raf.seek (StartIndex); System.out.println ("First" + ThreadId + "Threads: the start position of the Write file:" + string.valueof (startIndex)); int len = 0;byte[] buffer = new BYTE[512] ; while (len = Is.read (Buffer))! =-1) {//The reason for using this and not applicable fileoutputstream is because the FileOutputStream is likely to appear after the upload download has been disconnected after the data is still in the hard disk buffer, no real input to the hard disk, resulting in data loss.     The randomaccessfile is not only readable and writable, but also instantly updated for data. The second parameter needs to be rwdrandomaccessfile RF = new Randomaccessfile (Positionfile, "RWD"); raf.write (buffer, 0, Len);//The amount of data currently downloaded Total + = Len;rf.write (string.valueof (total) getBytes ()); Rf.close ();} Is.close (); Raf.close ();} catch (Exception e) {e.printstacktrace ();} finally {//the record file can only be deleted after all threads have been downloaded. Synchronized (Mutilethreaddownload.class) {System.out.println ("thread" + threadId + "Download Complete"); Runningthreadcount--;if ( Runningthreadcount < 1) {System.out.println ("All threads have finished working. Delete temporary record file "); for (int i = 1; I <= threadcount; i++) {File F = new file (i +". txt "); System.out.println (F.delete ());}}}}}}



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.