Java Multi-Threading download

Source: Internet
Author: User
Tags event listener time in milliseconds

The principle of multi-threaded download is that each thread downloads part of the file, each thread writes its own portion of the download to the file where it should be, and when all the threads download is complete, the file is downloaded. The key points are: Randomaccessfile.seek (beginindex) and Urlconnection.setrequestproperty ("Range", "bytes=" + beginindex + "-" + EndIndex).

Reproduced please specify the original address, please respect the original, thank you.

The code below, the following code copy can be run directly, can be used directly in Java or Android project (Android project version of the API is relatively low without connection.getcontentlengthlong () method, Need to change Connection.getcontentlengthlong () to Connection.getcontentlength ()):

Import Java.io.ioexception;import Java.io.inputstream;import Java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import java.util.eventobject;/** * Multi-threaded Downloader * * @author Tang * */public fin Al class Multithreaddownloader {/** * Test * * @param args * @throws ioexception */public static void Main (string[] args) t Hrows IOException {final Multithreaddownloader downloader = new Multithreaddownloader ("http://dlsw.baidu.com/ Sw-search-sp/soft/3a/12350/qq7.3.15034.0.1434079564.exe "," QQInstall.exe ");d Ownloader.setdownloadlistener (new Downloadlistener () {public void Undonedownload (Downloadevent event) {System.out.println ("Download not Completed");} public void Donedownload (Downloadevent event) {System.out.println ("Download Complete");} public void Progresschange (Downloadevent event) {System.out.println (); Multithreaddownloader downloader = (multithreaddownloader) event.getsource (); System.out.println ("Download progress:" + downloader.getprogress () + "%"); System.out.println ("Elapsed:" + (Downloader.getdonetime ()/1000) +"Seconds"); System.out.println ("Expected to still be taken:" + (Downloader.getundonetime ()/1000) + "seconds"); System.out.println ("Download speed:" + (Downloader.getdownloadspeed () * 1000/1024/1024) + "MB/S"); System.out.println ();}}); Downloader.startdownload ();} /** * Multi-threaded Download event listener */public static interface Downloadlistener {/** * Download complete notification */void Donedownload (downloadevent event);/** * Download Incomplete notifications */void Undonedownload (downloadevent event)/** * Download Progress change notification */void Progresschange (Downloadevent event);} /** * Multithreaded Download Event source */public Static class Downloadevent extends EventObject {private static final long Serialversionuid = 1l;pu Blic downloadevent (Object source) {super (source);}} /** * File Download URL path */private final String downloadpath;/** * file download URL */private final URL downloadurl;/** * Keep files to local file path */p Rivate final String savepath;/** * Randomaccessfile object constructed pattern, "RWD" means that this file can be read writable can be deleted */private final string fileMode = "RWD";/** * How many bytes per read */private final int bufferarrayinitialcapacity;/** * How many threads are started to download this file */private final int threadcount;/** * text when you download a file Pieces TotalByte size */private final long filecontentlength;/** * Read byte size */private long donebytelength;/** * remaining file total byte size */private long UN donebytelength;/** * Time to start the download, in milliseconds */private long begindownloadtime;/** * Time spent in milliseconds, unit: msec */private long donetime;/** * PRE Download time for remaining files in milliseconds */private long undonetime;/** * Download speed in bytes/msec */private double downloadspeed;/** * Download progress, value between 0~100, that is 0& lt;=progress<=100 */private Int progress;/** * Whether to pause download, pause download If true, reset to False to continue downloading */private boolean ispause;/** * Whether to close the download, if true, the download will be terminated */private boolean isclose;/** * Download Completed */private boolean isdone;/** * The thread used to hold all downloaded files */private final shareequallydownloadthread[] downloadthreads;/** * Download event listener */private downloadlistener downloadlistener;/** * Download Event source, The event source would have to be created each time, but this is the event source what properties are not, so in order to save memory only create a */private final downloadevent downloadevent = new Downloadevent (this);/** * @param downloadpath * File Download URL path * @param savepath * Keep files to local file path * @throws ioexception */public M Ultithreaddownloader (String Downloadpath, STring Savepath) throws IOException {This (Downloadpath, Savepath, 2048, ten, NULL);}            /** * @param downloadpath * File Download URL path * @param savepath * Keep files to local file path * @param threadcount * How many threads are started to download this file * @throws ioexception */public multithreaddownloader (String Downloadpath, string savepath, int THREADC Ount) throws IOException {This (Downloadpath, Savepath, 2048, threadcount, NULL);} /** * @param downloadpath * File Download URL path * @param savepath * Keep files to local file path * @param bufferarrayinitialc apacity * Length of bytes per read * @param threadcount * How many threads are started to download this file * @param downloadlistener * Download monitor Device * @throws IOException */public multithreaddownloader (String Downloadpath, String Savepath, Downloadlistener Downloadlistener) throws IOException {This (Downloadpath, Savepath, 2048, ten, Downloadlistener);} /** * @param downloadpath * File Download URL path * @param savepath * Keep files to local file path * @param bufferarrayinitialc            Apacity *Length of bytes per read * @param threadcount * How many threads are started to download this file * @param downloadlistener * Download listener * @throws Ioexcepti On */public multithreaddownloader (string Downloadpath, string savepath, int bufferarrayinitialcapacity, int threadCount , Downloadlistener Downloadlistener) throws IOException {This.downloadpath = Downloadpath;this.savepath = SavePath; this.bufferarrayinitialcapacity = Bufferarrayinitialcapacity;this.threadcount = Threadcount;this.downloadlistener = Downloadlistener;downloadthreads = new Shareequallydownloadthread[threadcount];d ownloadurl = new URL (DownloadPath); HttpURLConnection connection = (httpurlconnection) downloadurl.openconnection (); int responsecode = Connection.getresponsecode (); if (responsecode! = HTTPURLCONNECTION.HTTP_OK) {throw new IOException ("URL:" + Downloadpath + "Responsecode is" + Responsecode);} Filecontentlength = Connection.getcontentlengthlong (), if (Filecontentlength < 0) {throw new IOException ("URL:" + Downloadpath + "Download file contentLength less than 0! ");} if (Filecontentlength = = 0) {throw new IOException ("URL:" + downloadpath + "Download file content length equals 0!");} Try (randomaccessfile randomaccessfile = new Randomaccessfile (Savepath, FileMode)) {Randomaccessfile.setlength ( FILECONTENTLENGTH);//Specifies the length of the file created} catch (IOException e) {throw e;} finally {connection.disconnect ();} The average size of files downloaded per thread. Long threadshareequallybytelength = filecontentlength/threadcount;for (int i = 0; i < ThreadCount; i++) {//Java in front of package Not after the principle of the package, so endIndex do not reduce the 1long beginindex = i * threadshareequallybytelength;//to prevent the sharing of surplus, the remainder portion of the file bytes to the last thread long EndIndex = i & Lt (threadCount-1)? Beginindex + threadshareequallybytelength:filecontentlength;downloadthreads[i] = new Shareequallydownloadthread ( Beginindex, EndIndex);}} /** * The thread responsible for downloading and saving a portion of the file */private final class Shareequallydownloadthread extends thread {private final long beginindex;pri Vate Final Long Endindex;private boolean isdone;private httpurlconnection connection;private RANDOMACCEssfile randomaccessfile;public Shareequallydownloadthread (Long beginindex, long endIndex) {This.beginindex = Beginindex;this.endindex = EndIndex;} @Overridepublic void Run () {try {connection = (HttpURLConnection) downloadurl.openconnection (); Connection.setrequestproperty ("Range", "bytes=" + beginindex + "-" + endIndex);//Download a portion of the file, the package before the package after try (inputstream InputStream = Connection.getinputstream (); Randomaccessfile randomaccessfile = new Randomaccessfile (Savepath, FileMode)) {this.randomaccessfile = Randomaccessfile;randomaccessfile.seek (beginindex);//jump to the specified file location byte[] bufferbytes = new byte[ Bufferarrayinitialcapacity];int readbytelength = Inputstream.read (bufferbytes);//Read while (Readbytelength > 0 && amp;!isclose) {if (ispause) {//pause continue;} Randomaccessfile.write (bufferbytes, 0, readbytelength);//write Donetime = System.currenttimemillis ()-BeginDownloadTime ;//Statistics Time of use//each will read the length of the bytes accumulated recorded donebytelength + = Readbytelength;undonebytelength = filecontentlength-donebytelength;// The downloaded file is calculated to account forPercent of total files int percentcompleted = (int) (DONEBYTELENGTH * 100.0/filecontentlength);p ercentcompleted = Math.min (Math.max ( percentcompleted, 0), UpdateProgress (percentcompleted);//update Progress readbytelength = Inputstream.read (bufferBytes); /Continue reading}isdone = True;if (Downloadlistener! = null && isDone ()) {if (Isclose | | ispause) {Downloadlistener.undonedow Nload (downloadevent);} else {downloadlistener.donedownload (downloadevent);}}} catch (Exception e) {throw new RuntimeException (e);} finally {connection.disconnect ();}} catch (IOException e) {throw new RuntimeException (e);}} /** * Force destroy connection and close file stream */public void Destroyconnectionandclosestream () {if (connection! = null) {connection.disconnect (); try {Connection.getinputstream (). Close ();} catch (Exception e) {e.printstacktrace ();}} if (randomaccessfile! = null) {try {randomaccessfile.close ();} catch (IOException e) {e.printstacktrace ();}}}} /** * Calculate download speed and remaining download time */private void Updatedownloadspeedandundonetime () {downloadspeed = Donebytelength/donetiMe * 1.0;undonetime = (long) (undonebytelength/downloadspeed);}  /** * Update Progress * * @param progress */private void UpdateProgress (int progress) {if (this.progress! = progress) {This.progress = Progress;updatedownloadspeedandundonetime (); if (downloadlistener! = null) {Downloadlistener.progresschange ( downloadevent);}}} /** * Start download */public void Startdownload () {begindownloadtime = System.currenttimemillis (); for (int i = 0; i < downloadth Reads.length; i++) {Downloadthreads[i].start ();}} Public String Getdownloadpath () {return downloadpath;} /** * Get File total byte size * * @return */public long getfilecontentlength () {return filecontentlength;} Public String Getsavepath () {return savepath;} public int getbufferarrayinitialcapacity () {return bufferarrayinitialcapacity;} public int Getthreadcount () {return threadcount;} /** * File Download Complete * * @return */public boolean isDone () {if (IsDone) {return isDone;} for (int i = 0; i < downloadthreads.length; i++) {if (!downloadthreads[i].isdone) {return false;}} Returntrue;} /** * Get download progress, value between 0~100, that is 0<=progress<=100 * * @return */public int getprogress () {return progress;} /** * Pause Download */public void Pausedownload () {this.ispause = true;} /** * Resume Download */public void Restoredownload () {this.ispause = false;} public Boolean ispause () {return ispause;} /** * Close Download, download will be terminated */public void Closedownload () {if (isclose) {return;} Isclose = true;for (int i = 0; i < downloadthreads.length; i++) {Downloadthreads[i].destroyconnectionandclosestream (); }}public Boolean isclose () {return isclose;} Public URL Getdownloadurl () {return downloadurl;} /** * Gets the read byte size * * @return */public long getdonebytelength () {return donebytelength;} /** * Get remaining file total byte size * * @return */public long getundonebytelength () {return undonebytelength;} /** * Gets the time spent on completion, in milliseconds * * @return */public long getdonetime () {return donetime;} /** * Get remaining file download time in milliseconds * * @return */public long getundonetime () {return undonetime;} /** * Get download speed in bytes/msec * * @return */public double getdownloadspeed () {return DowNloadspeed;} /** * Get Download Event listener * * @return */public downloadlistener Getdownloadlistener () {return downloadlistener;}  /** * Set Download Event listener * * @return */public void Setdownloadlistener (Downloadlistener downloadlistener) {This.downloadlistener = Downloadlistener;}}


Java Multi-Threading 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.