Java single-threaded file download, support for breakpoint continuation function

Source: Internet
Author: User

Objective:

program download files, sometimes because of a variety of reasons to download the interruption, small files have little impact, can be quickly re-download, but when downloading large files, it will take a long time, so the breakpoint continuation function for large files is necessary.

File download of the breakpoint continue to pass:

 1, first download temporary files, used to record the downloaded size:

2. Set the range parameter when HTTP requests

3, download the data of this request;

Directly on the code:

1  PackageCom.test.service;2 3 ImportJava.io.File;4 ImportJava.io.InputStream;5 ImportJava.io.RandomAccessFile;6 Importjava.net.HttpURLConnection;7 ImportJava.net.URL;8 ImportJava.text.NumberFormat;9 Ten ImportOrg.slf4j.Logger; One Importorg.slf4j.LoggerFactory; A ImportOrg.springframework.beans.factory.annotation.Value; - Importorg.springframework.stereotype.Component; -  the /** - * <p> - * File download, can support the continuation of the breakpoint - * Not used at this stage + * </p> -  *  @author  +  *  @version1.0 A  * */ at @Component -  Public classdownloadonly { -  -     Private Static FinalLogger Logger = Loggerfactory.getlogger (downloadonly.class); -      -@Value ("${onair.download.ddxc:true}") in     BooleanDDXC =true; -      to     intStartIndex = 0; +      -     LongDownloadsize = 0; the      *     BooleanDownloadfinish =false; $     Panax Notoginseng     intTotlesize = 0; -      the      Public BooleanDownload (String url,string File_path,intdownloadtimeout) { +  A         //start a thread to detect the download progress the         NewThread (NewRunnable () { +              - @Override $              Public voidrun () { $                 Try { -NumberFormat NT =numberformat.getpercentinstance ();  -                       //Set percent accuracy 3 to retain three decimal places theNt.setminimumfractiondigits (1);  -                      while(!downloadfinish) {WuyiThread.Sleep (30000); theLogger.debug ("Downloaded size {}, Progress {}", Getdownloadsize (), Nt.format (Getdownloadsize () * 1.0/totlesize)); -                     } Wu}Catch(interruptedexception e) { - e.printstacktrace (); About                 } $                  -             } - }). Start (); -          ALogger.info ("Download file: Source path {}, Destination path: {}", Url,file_path); +Randomaccessfile RAF =NULL; theInputStream in =NULL; -          $         Try { theURL File_url =Newurl (url); theHttpURLConnection conn =(HttpURLConnection) file_url.openconnection (); the conn.setconnecttimeout (downloadtimeout); theConn.setrequestmethod ("GET"); -File tmpfile =NewFile (file_path+ "_tmp"); in             if(DDXC) { the                 if(Tmpfile.exists () &&Tmpfile.isfile ()) { theDownloadsize =tmpfile.length (); AboutStartIndex = (int) downloadsize; the                 } theConn.setrequestproperty ("Range", "bytes=" + StartIndex + "-"); the}Else{ +                 if(Tmpfile.exists () &&tmpfile.isfile ()) - Tmpfile.delete (); the             }Bayi             intStatus =Conn.getresponsecode (); theTotlesize = (int) Downloadsize +conn.getcontentlength (); theLogger.info ("Total file size {}, download request for return status code: {}, size required to download {}", totlesize,status,totlesize-downloadsize); -             if(status== | | status = = 206 ){ -RAF =NewRandomaccessfile (Tmpfile, "RWD"); the Raf.seek (startIndex); thein =Conn.getinputstream (); the                 byte[] buffer =New byte[1024]; the                 intSize = 0; -                  while(Size=in.read (buffer))!=-1 ){ theRaf.write (buffer, 0, size); theDownloadsize + =size; the                 }94 raf.close (); the in.close (); theFile dest =NewFile (file_path); the                 returnTmpfile.renameto (dest);98             } About}Catch(Throwable e) { -Logger.error ("File download failed: {}", E.getmessage (), e);101}finally {102Downloadfinish =true;//download Complete or interrupted103         }104         return false; the     }106 107      Public Longgetdownloadsize () {108         returndownloadsize;109     } the     111      Public Static voidMain (string[] args) { theDownloadonly downloadonly =Newdownloadonly ();113     } the      the}

Java single-threaded file download, support for breakpoint continuation function

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.