Java implementation Multi-threaded file Download (HTTP)

Source: Internet
Author: User

Implementation principle:

Use Httpconnection.setrequestproperty ("RANGE", "bytes= xxx-xxx") to get the specified data block

Use Randomaccessfile to implement random access to the file, write the specified data block to the file.

Key issue: Get the remote file size, determine the number of download threads depending on the size of the file (number of threads can be fixed, or you can pin each thread to download the chunk size, as the user decides).

 Packageorg.hundred.multithreads;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL;/*** File Download management class*/ Public classDownloadmanager {/*** Number of bytes downloaded per thread*/    Static Final Longunitsize = 1000 * 1024; /*** Start multiple threads to download files*/     Public voiddodownload (String remotefileurl)throwsIOException {String fileName=NewURL (Remotefileurl). GetFile (); FileName= Filename.substring (Filename.lastindexof ("/") +1,filename.length ()). Replace ("%20", "" "); LongFileSize = This. Getremotefilesize (Remotefileurl); if(FileSize = = 0){            return; }                This. CreateFile (FileName, fileSize); LongThreadCount = fileSize/unitsize; System.out.println ("Co-start" + (fileSize% UnitSize = = 0?) Threadcount:threadcount + 1)                + "Threads"); LongOffset = 0; if(FileSize <= unitsize) {//if the remote file size is less than or equal to UnitSizeDownloadthread Downloadthread=NewDownloadthread (Remotefileurl, FileName, offset, fileSize);        Downloadthread.start (); } Else{//if the remote file size is greater than unitsize             for(inti = 1; I <= threadcount; i++) {Downloadthread Downloadthread=NewDownloadthread (Remotefileurl, FileName, offset, unitsize);                 Downloadthread.start (); Offset= offset +unitsize; }            if(fileSize% UnitSize! = 0) {//If not divisible, you need to create another thread to download the remaining bytesDownloadthread Downloadthread=NewDownloadthread (Remotefileurl, FileName, offset, fileSize-UnitSize *threadcount);             Downloadthread.start (); }        }     }     /*** Get remote file size*/    Private LongGetremotefilesize (String Remotefileurl)throwsIOException {LongFileSize = 0; HttpURLConnection httpconnection= (httpurlconnection)NewURL (Remotefileurl). OpenConnection (); Httpconnection.setrequestmethod ("HEAD"); intResponsecode =Httpconnection.getresponsecode (); if(Responsecode >= 400) {System.out.println ("Web server response Error!"); return0;        } String Sheader;  for(intI=1;; i++) {Sheader=Httpconnection.getheaderfieldkey (i); if(Sheader! =NULL&& sheader.equals ("Content-length") {System.out.println ("File size contentlength:" +httpconnection.getcontentlength ()); FileSize=Long.parselong (Httpconnection.getheaderfield (Sheader));  Break; }        }         returnfileSize; }     /*** Create a file of the specified size*/    Private voidCreateFile (String FileName,LongFileSize)throwsIOException {File newFile=NewFile (fileName); Randomaccessfile RAF=NewRandomaccessfile (NewFile, "RW");         Raf.setlength (fileSize);    Raf.close (); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// Packageorg.angus.multithreads;ImportJava.io.BufferedInputStream;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL;/*** The class responsible for file download*/ Public classDownloadthreadextendsThread {/*** files to be downloaded*/    PrivateString URL =NULL; /*** Local file name*/    PrivateString FileName =NULL; /*** Offset Amount*/    Private LongOffset = 0; /*** Number of downloaded bytes allocated to this thread*/    Private LongLength = 0; /**     * @paramURL Download file address *@paramFileName Save file name *@paramoffset this thread download offsets *@paramlength of this thread download * *@authorAngus.wang **/     PublicDownloadthread (string url, string file,LongOffsetLonglength) {         This. url =URL;  This. FileName =file;  This. offset =offset;  This. length =length; System.out.println ("offset =" + offset + "byte number =" +length); }      Public voidrun () {Try{httpurlconnection httpconnection= (httpurlconnection)NewURL ( This. url). OpenConnection (); Httpconnection.setrequestmethod ("GET"); Httpconnection.setrequestproperty ("RANGE", "bytes=" + This. Offset+ "-" + ( This. Offset + This. length-1)); System.out.println ("RANGE bytes=" + This. Offset + "-" + ( This. Offset + This. length-1)); Bufferedinputstream bis=NewBufferedinputstream (httpconnection. getInputStream ()); byte[] Buff =New byte[1024]; intBytesread; File NewFile=NewFile (fileName); Randomaccessfile RAF=NewRandomaccessfile (NewFile, "RW");  while((bytesread = bis.read (buff, 0, buff.length))! =-1) {Raf.seek ( This. Offset); Raf.write (Buff,0, Bytesread);  This. offset = This. Offset +Bytesread;            } raf.close ();        Bis.close (); } Catch(IOException IoE) {ioe.printstacktrace (); }     } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// Packageorg.angus.multithreads;/*** Multi-threaded file download Test **/ Public classFiledownloadtest {/**     * @paramargs*/     Public Static voidMain (string[] args) {Try{String Remotefileurl= "Http://dl.maxthon.cn/cn/mx2/mx_2.5.1.4751cn.exe"; Downloadmanager Downloadmanager=NewDownloadmanager ();        Downloadmanager.dodownload (Remotefileurl); }Catch(Exception e) {e.printstacktrace (); }            } }

Java implementation Multi-threaded file Download (HTTP)

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.