package com.download;import java.io.file;import java.io.inputstream;import Java.io.randomaccessfile;import java.net.httpurlconnection;import java.net.url;public class MutileThreadDown {private static int blockCount=3;private static int Blocksize;public static void main (String[] args) throws Exception{String Path= "Http://localhost:8080/Web025Server/media/bootstrap.avi"; Url url=new url (path); Httpurlconnection conn= (HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (10000); Conn.setreadtimeout (n); Int responsecode=conn.getresponsecode (); if ( responsecode==200) {int size=conn.getcontentlength (); SYSTEM.OUT.PRINTLN ("server-side Length" +size) blocksize=size/blockcount;//Create a blank file that is the same size as the server side File file=new file ( "Aa.avi"); Randomaccessfile raf=new randomaccessfile (file, "RW"); raf.setlength (size);//sets the size of the file//2. Turn on several sub-threads, respectively download resources for (int i=1;i<=blockcount;i++) {int startindex= (i-1) *blocksize+0;int endindex=i* Blocksize-1;if (i==blockcount) {endindex=size-1;} New downloadthread (Startindex, endindex, i, path). Start (); SYSTEM.OUT.PRINTLN ("Open thread" +i+ "start position" +startindex+ "End position is" +endindex ");}} Conn.disconnect ();} Defines an internal class for a thread private static class downloadthread extends thread{private int Startindex;private int endindex;private int threadi;private string path;public downloadthread (Int startindex, int endindex, int threadi,string path) {super (); this.startindex = startindex;this.endindex = endindex;this.threadi = threadi;this.path = path;} @Overridepublic void run () {try {string path= "http://localhost:8080/Web025Server/ Media/bootstrap.avi "; Url url=new url (path); Httpurlconnection conn= (httpurlconnection) &NBsp;url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Range", "bytes=" + startindex+ "-" +endindex); Conn.setconnecttimeout (10000); conn.setreadtimeout; int responsecode= Conn.getresponsecode (); SYSTEM.OUT.PRINTLN ("Server response Code" +responsecode);//Create a blank file File file=new file ("Aa.avi") with the same size as the server side; Randomaccessfile raf=new randomaccessfile (file, "RW"); Inputstream in=conn.getinputstream (); Raf.seek (StartIndex);//Where to start writing the file Int len=-1;byte[] bytes=new byte[1024];while (Len=in.read ( bytes)) (!=-1) {raf.write (Bytes, 0, len);} In.close (); Raf.close ();} catch (exception e) {e.printstacktrace ();} }}}
This article is from the "Java White Battlefield" blog, be sure to keep this source http://8023java.blog.51cto.com/10117207/1670663
multithreaded Download in Java