Multi-Threaded Download

Source: Internet
Author: User

implementing this function requires a class randomaccessfile, which is neither inherited from InputStream nor inherited from OutputStream,
Directly inherit from the object class, it can be implemented in the file back and forth, moving in the file with Seek (), you can use in the file to insert data
or overwrite some data, skipping how many bytes with skipbytes (), this can be used to implement multi-threaded download.
Write all download operations in a class, first use Httourlconnection to get the file size according to the URL of the file, and then according to the storage path
and size with Randomaccessfile to initialize a file (for storing files), and then assign each thread according to the number of threads set to download multiple
Large file, first starting from 0 bytes, the second jump out of the first thread to download the file byte size, from each line thread executes downloaded file size there start, and so on,

Here is a small example.

Import Java.io.inputstream;import java.io.randomaccessfile;import java.net.httpurlconnection;import Java.net.URL; Public class downutil{//defines the path to the download resource private string path;//specifies the location where the downloaded file is saved private string targetfile;// Defines how many threads need to be used to download the resource private int threadnum;//defines the downloaded thread object private downthread[] threads;//defines the total size of the downloaded file private int filesize;public Downutil (string path, string targetfile, int threadnum) {This.path = Path;this.threadnum = threadnum;// Initialize threads Array threads = new Downthread[threadnum];this.targetfile = TargetFile;} public void Download () throws Exception{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Accept", "Image/gif, Image/jpeg, Image/pjpeg, image/pjpeg," + "Application/x-shockwave-flash, Application/xaml+xml," + "application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP," + "Application/x-ms-application, Application/vnd.ms-excel," + "Application/vnd.ms-powerpoint, APPlication/msword, */* "), Conn.setrequestproperty (" Accept-language "," ZH-CN "), Conn.setrequestproperty (" Charset "," UTF-8 "); Conn.setrequestproperty (" Connection "," keep-alive ");//Get file size FileSize = Conn.getcontentlength (); Conn.disconnect (); int currentpartsize = Filesize/threadnum + 1; Randomaccessfile file = new Randomaccessfile (targetfile, "RW");//Set the size of local files file.setlength (fileSize); File.close (); for (int i = 0; i < threadnum; i++) {//Calculate the start of each thread's download int startpos = i * currentpartsize;//each thread uses a randomaccessfile to download randomaccessfile currentpart = new Ra Ndomaccessfile (TargetFile, "RW");//Locate the thread's download location Currentpart.seek (startpos);//create download thread threads[i] = new Downthread ( Startpos, Currentpartsize,currentpart);//Start Download thread Threads[i].start ();}} Gets the percent complete of the download public double getcompleterate () {//Statistics multiple threads have downloaded a total size of int sumsize = 0;for (int i = 0; i < threadnum; i++) {Sumsi Ze + = threads[i].length;} Returns the percentage that has been completed return sumsize * 1.0/filesize; Private class Downthread extends thread{//the current thread's download location private int startpos;//Defines the file size that the current thread is responsible for downloading private int currentpartsize;//the file block that the current thread needs to download private Randomaccessfile currentpart;// Defines the number of bytes that have been downloaded by this thread public int length;public downthread (int startpos, int currentpartsize,randomaccessfile currentpart) { This.startpos = Startpos;this.currentpartsize = Currentpartsize;this.currentpart = Currentpart;} @Overridepublic void Run () {try{url url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Accept", "Image/gif, Image/jpeg, Image/pjpeg, image/pjpeg," + "Application/x-shockwave-flash, Application/xaml+xml," + "application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP," + "Application/x-ms-application, Application/vnd.ms-excel," + "Application/vnd.ms-powerpoint, Application/msword, */* "); Conn.setrequestproperty (" Accept-language "," ZH-CN "); Conn.setrequestproperty (" Charset "," UTF-8 "); InputStream Instream = Conn.getinputstream ();//skips startpos bytes, indicating that the thread only downloads which part of the file it is responsible for. Instream.skip (This.startpos); byte[] buffer = new Byte[1024];int Hasread = 0;//Reads network data and writes to local file while (length < currentpartsize&&am P (Hasread = instream.read (buffer)) > 0) {System.out.println (Hasread + "); currentpart.write (buffer, 0, hasread);// Accumulate the total size of the thread download length + = Hasread;} Currentpart.close (); Instream.close ();} catch (Exception e) {e.printstacktrace ();}}}}

Import Java.util.timer;import java.util.timertask;import Android.app.activity;import Android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.edittext;import Android.widget.progressbar;public class Multithreaddown extends Activity{edittext URL; EditText Target; Button downbn; ProgressBar bar;downutil downutil;private int mdownstatus; @Overridepublic void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.main);//Gets the three interface control URL in the program interface = (EditText) Findviewbyid ( R.id.url); target = (EditText) Findviewbyid (r.id.target);d ownbn = (Button) Findviewbyid (r.id.down); bar = (ProgressBar) Findviewbyid (R.id.bar);//Create a Handler object final Handler Handler = new Handler () {@Overridepublic void Handlemessage ( Message msg) {if (Msg.what = = 0x123) {bar.setprogress (mdownstatus);}}}; Downbn.setonclicklistener (New Onclicklistener () {@Overridepublic void ONclick (View v) {//Initialize Downutil object (the last parameter specifies the number of threads) Downutil = new Downutil (Url.gettext (). toString (), Target.gettext (). ToString (), 6); new Thread () {@Overridepublic void run () {try{//start download downutil.download ();} catch (Exception e) {e.printstacktrace ();} Define scheduling per second gets the complete progress of the system final Timer timer = new timer (); Timer.schedule (new TimerTask () {@Overridepublic void Run () {// Gets the completion ratio of the download task double completerate = Downutil.getcompleterate (); mdownstatus = (int) (completerate * 100);// Send Message Notification interface update progress bar handler.sendemptymessage (0x123);//download complete after canceling task dispatch if (Mdownstatus >=) {timer.cancel ();}}, 0, 100);}}. Start ();}});}}


Multi-Threaded 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.