Java Imitation Thunder multi-threaded download

Source: Internet
Author: User

 PackageNet.webjoy.jackluo.android_json;/*** 1.http Range "bytes=" + start+end * 2.RandomAccessFile Set Write location * 3 turn on multi-threaded download * * Created by Jackluo on 9/30/15. */Importandroid.os.Environment;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;ImportJava.util.concurrent.Executor;Importjava.util.concurrent.Executors;/*** Multi-threaded Download*/ Public classDownLoad {//Create a thread pool create three threads    PrivateExecutor ThreadPool = Executors.newfixedthreadpool (3); PrivateHandler Handler;  PublicDownLoad (Handler Handler) { This. Handler =handler; }    //Create a thread pool object    Static classDownloadrunnableImplementsrunnable{PrivateString URL; PrivateString FileName; Private LongStart;//Start Position        Private LongEnd//End Position        PrivateHandler Handler;  PublicDownloadrunnable (String url,string fileName,LongStartLongEnd,handler Handler) {             This. url =URL;  This. FileName =FileName;  This. Start =start;  This. end =end;  This. Handler =handler; } @Override Public voidrun () {Try{URL Httpurl=Newurl (URL); HttpURLConnection Connection=(HttpURLConnection) httpurl.openconnection (); Connection.setrequestmethod ("GET"); Connection.setreadtimeout (5000); //set the download location to get the specified stream information to the serverConnection.setrequestproperty ("Range", "bytes=" + Start + "-" +end); //create a file to write information from a specified locationRandomaccessfile Accessfile =NewRandomaccessfile (NewFile (FileName), "rwx"); Accessfile.seek (start);//setting the location to read and writeInputStream InputStream =Connection.getinputstream (); byte[] B =New byte[1024*4];//set the size of the buffer to save                intLen=0;  while(len = Inputstream.read (b))!=-1) {Accessfile.write (b,0, Len); }                if(Accessfile! =NULL) {accessfile.close (); }                if(InputStream! =NULL) {inputstream.close (); }                //send a message to the main threadMessage message =NewMessage (); Message.what= 1;            Handler.sendmessage (message); } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        }    }     Public voiddownLoadFile (String url) {Try{URL Httpurl=Newurl (URL); HttpURLConnection Connection=(HttpURLConnection) httpurl.openconnection (); Connection.setrequestmethod ("GET"); Connection.setreadtimeout (5000); intCount = Connection.getcontentlength ();//gets the size of the picture            intblock = COUNT/3; //calculate the start position of the threadString FileName =getfilename (URL); File Parent=environment.getexternalstoragedirectory (); File FileDownload=NewFile (parent,filename); /*** 11/3 = 3 bytes per download 3 more than 2 bytes of space * First thread 0-2 * Second thread 3-5 * Third thread 6-10 *             *             */             for(inti=0;i<3;i++){                LongStart = i*Block; LongEnd = (i+1) *block-1; if(i==2) {End=count; } downloadrunnable runnable=Newdownloadrunnable (URL, Filedownload.getabsolutepath (), Start,end,handler); //Submit a TaskThreadpool.execute (runnable); }        } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }    /*** Get URL suffix name*/     Publicstring getfilename (string url) {returnUrl.substring (Url.lastindexof ("/") +1); }}
 PackageNet.webjoy.jackluo.android_json;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classDownloadactivityextendsappcompatactivity {Privatebutton button; PrivateTextView TextView; Private intCount =1; PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {//super.handlemessage (msg);            intresult =Msg.what; Count+=result; if(count==3) {Textview.settext ("Download Success");    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_down_load); Button=(Button) Findviewbyid (R.ID.DOWNLAD_BTN); TextView=(TextView) Findviewbyid (R.id.textview); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {DownLoad load=NewDownLoad (handler); Load.downloadfile ("Http://news.jsyks.com/photo/img1a.xgo-img.com.cn/pics/737/736406.jpg");            }}.start ();    }        }); }}

Java Imitation Thunder 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.