Java multi-threaded download file and breakpoint download

Source: Internet
Author: User

ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importjavax.print.attribute.standard.Finishings; Public classMultidownload {Static intThreadCount = 3;//represents 3 Processes    Static intFinishedthread = 0;//record the number of files that are finished//Determine    StaticString Path = "Http://192.168.13.13:8080/QQPlayer.exe";  Public Static voidMain (string[] args) {//send a GET request to request resources for this address        Try{URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); if(Conn.getresponsecode () = = 200){                //get the length of the requested resource file                intLength =conn.getcontentlength (); File File=NewFile ("QQPlayer.exe"); //Generate temporary FilesRandomaccessfile RAF =NewRandomaccessfile (file, "RWD"); //set the size of a temporary fileraf.setlength (length);                Raf.close (); //calculate how many bytes each thread should download                intSize = length/ThreadCount;  for(inti = 0; i < ThreadCount; i++) {                    //calculate start and end locations for thread downloads                    intStartIndex = i *size; intEndIndex = (i + 1) * size-1; //if it is the last thread, then the end position is written dead                    if(i = = ThreadCount-1) {EndIndex= Length-1; }//System.out.println ("thread" + i + "Download interval is:" + StartIndex + "---" + endIndex);                    NewDownloadthread (StartIndex, EndIndex, i). Start (); }            }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }        }classDownloadthreadextendsthread{intStartIndex; intEndIndex; intthreadId;  PublicDownloadthread (intStartIndex,intEndIndex,intthreadId) {        Super();  This. StartIndex =StartIndex;  This. EndIndex =EndIndex;  This. ThreadId =threadId; } @Override Public voidrun () {//send HTTP request again, download original file        Try{File Progressfile=NewFile (threadId + ". txt"); //determine if the progress temp file exists            if(Progressfile.exists ()) {FileInputStream fis=NewFileInputStream (Progressfile); BufferedReader BR=NewBufferedReader (NewInputStreamReader (FIS)); //read the total progress of the last download from the progress temp file and add it to the original starting position to get a new start positionStartIndex + =Integer.parseint (Br.readline ());            Fis.close (); } System.out.println (The download interval for "thread" + ThreadId + "is:" + StartIndex + "---" +EndIndex);            HttpURLConnection Conn; URL URL=NewURL (Multidownload.path); Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); //sets the interval of data requested by this HTTP requestConn.setrequestproperty ("Range", "bytes=" + StartIndex + "-" +EndIndex); //request part of the data, the corresponding code is 206            if(Conn.getresponsecode () = = 206){                //There's only 1/3 data in the stream at this time.InputStream is =Conn.getinputstream (); byte[] B =New byte[1024]; intLen = 0; intTotal = 0; //get the output stream for the temp fileFile File =NewFile ("QQPlayer.exe"); Randomaccessfile RAF=NewRandomaccessfile (file, "RWD"); //move the file's write location to startindexRaf.seek (StartIndex);  while(len = Is.read (b))! =-1){                    //synchronously writes data to a temporary file after each reading of the data in the streamRaf.write (b, 0, Len); Total+=Len;//System.out.println ("Threads" + threadId + "downloaded" + total); //generate a temporary file dedicated to recording the download progressRandomaccessfile Progressraf =NewRandomaccessfile (Progressfile, "RWD"); //synchronously writes the total progress of the current thread download to the progress temp file after each reading of the data in the streamProgressraf.write (Total + ""). GetBytes ());                Progressraf.close (); } System.out.println ("Thread" + threadId + "Download-------------------the little volunteers! ");                                Raf.close (); //Delete the file of the recording process must all 3 processes download complete before you can deletemultidownload.finishedthread++; synchronized(Multidownload.path) {//thread security issues, static variables are unique                    if(Multidownload.finishedthread = =Multidownload.threadcount) {                         for(inti = 0; i < Multidownload.threadcount; i++) {File F=NewFile (i + ". txt");                        F.delete (); } multidownload.finishedthread= 0; }                }                            }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Java multi-threaded download file and breakpoint 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.