1 PackageCn.test.DownLoad;2 3 ImportJava.io.File;4 ImportJava.io.InputStream;5 ImportJava.io.RandomAccessFile;6 Importjava.net.HttpURLConnection;7 ImportJava.net.URL;8 9 Public classMultiPart {Ten Public voidDown ()throwsException One { A //1. Declaration URL -String filename= "A.rar"; -String path= "http://localhost:8080/day23_MultiThreadDownLoad/file/" +FileName; theURL url=NewURL (path); - //2. Return to the Connection object -HttpURLConnection conn=(HttpURLConnection) url.openconnection (); - //3. Set the request type +Conn.setrequestmethod ("GET"); - //4. Set allow messages to be received +Conn.setdoinput (true); A //5. Connection at Conn.connect (); - //6. Status Code - intCode=Conn.getresponsecode (); - if(code==200) - { - intSum=conn.getcontentlength ();//Total length inString downfile= "d:\\" +FileName; - //7. Create an empty file of the same size toRandomaccessfile file=NewRandomaccessfile (NewFile (Downfile), "RW"); + file.setlength (sum); - file.close (); the //8. Declaring the number of threads * intThreadcount=3; $ //9. Declare the download volume for each threadPanax Notoginseng intthreadsize=sum/threadcount+ ((sum%threadcount==0)? 0:1); - for(inti=0;i<threadcount;i++) the { + intstart=i*threadsize; A intEnd=start+threadsize-1; theSystem.out.println ("Thread:" +i+ ":" +start+ ":" +end); + //10. Start Thread - NewMyThread (Start,end,downfile,url). Start (); $ } $ } - //11. Close the connection - Conn.disconnect (); the } - Wuyi Public Static voidMain (string[] args) { the Try { - NewMultiPart (). Down (); Wu}Catch(Exception e) { - e.printstacktrace (); About } $System.out.println ("OK"); - } - } - A classMyThreadextendsThread + { the Private intstart; - Private intend; $ PrivateString Downfile; the PrivateURL url; the PublicMyThread (intStartintend, String downfile, url url) { the This. Start =start; the This. end =end; - This. Downfile =Downfile; in This. url =URL; the } the About Public voidrun () { the Try { theHttpURLConnection conn=(HttpURLConnection) url.openconnection (); theConn.setrequestmethod ("GET"); +Conn.setdoinput (true); - //settings from where to download. Breakpoint theConn.setrequestproperty ("Range", "bytes=" +start+ "-" +end);Bayi Conn.connect (); the intCode=Conn.getresponsecode (); the if(code==206) - { - intSize=conn.getcontentlength (); theInputStream in=Conn.getinputstream (); the //write the same file theRandomaccessfile file=NewRandomaccessfile (NewFile (Downfile), "RW"); the //set where to start writing from a file - File.seek (start); the byte[] b=New byte[1024]; the intLen=-1; the while((Len=in.read (b))!=-1)94 { theFile.write (b, 0, Len); the } the file.close ();98 } About Conn.disconnect (); - 101}Catch(Exception e) {102 e.printstacktrace ();103 } 104 } the}
Java implementation multi-threaded download