PackageSSS;Importjava.io.IOException;Importjava.util.Date; Public classTest1 { Public Static voidMain (string[] args) {Date startdate=NewDate (); Downloadfilewiththreadpool Pool=NewDownloadfilewiththreadpool (); Try{Pool.getfilewiththreadpool ("Http://mpge.5nd.com/2016/2016-11-15/74847/1.mp3", "D:\\1.mp3", 100); } Catch(IOException e) {e.printstacktrace (); } System.out.println (NewDate (). GetTime ()-startdate.gettime ()); }}
PackageSSS;Importjava.io.IOException;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;//Define thread pool Public classDownloadfilewiththreadpool { Public voidGetfilewiththreadpool (String urllocation, String FilePath,intPoollength)throwsIOException {executorservice ThreadPool=Executors.newcachedthreadpool (); LongLen =getcontentlength (urllocation); System.out.println (len); for(inti = 0; i < poollength; i++) {//divided into 100 segments Longstart = i * Len/poollength; LongEnd = (i + 1) * len/poollength-1; if(i = = PoolLength-1) {End=Len; } System.out.println (Start+"---------------"+end); Downloadwithrange Download=NewDownloadwithrange (urllocation, FilePath, start, end); Threadpool.execute (download); } threadpool.shutdown (); } Public Static LongGetcontentlength (String urllocation)throwsioexception {URL url=NULL; if(Urllocation! =NULL) {URL=NewURL (urllocation); } httpurlconnection Conn=(HttpURLConnection) url.openconnection (); Conn.setreadtimeout (50000); Conn.setrequestmethod ("GET"); LongLen =conn.getcontentlength (); returnLen; }}
PackageSSS;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classDownloadwithrangeImplementsRunnable {PrivateString urllocation; PrivateString FilePath; Private Longstart; Private Longend; Downloadwithrange (String urllocation, String FilePath,LongStartLongend) { This. urllocation =urllocation; This. FilePath =FilePath; This. Start =start; This. end =end; } @Override Public voidrun () {Try{HttpURLConnection conn=gethttp (); Conn.setrequestproperty ("Range", "bytes=" + Start + "-" +end); File File=NewFile (FilePath); Randomaccessfile out=NULL; if(File! =NULL) { out=NewRandomaccessfile (file, "RW"); } out.seek (start); InputStream in=Conn.getinputstream (); byte[] B =New byte[1024]; intLen = 0; while(len = In.read (b)) >= 0) {Out.write (b,0, Len); } in.close (); Out.close (); } Catch(Exception e) {e.getmessage (); } } PublicHttpURLConnection Gethttp ()throwsioexception {URL url=NULL; if(Urllocation! =NULL) {URL=NewURL (urllocation); } httpurlconnection Conn=(HttpURLConnection) url.openconnection (); Conn.setreadtimeout (50000); Conn.setrequestmethod ("GET"); returnConn; }}
Multi-Threaded download files