Multi-thread download in java

Source: Internet
Author: User

Multi-thread download in java
Multi-threaded download can seize the network resources (bandwidth) of other users with the same priority. Therefore, the download speed is faster, and multiple threads are used for downloading thunder and quickplay.
Vc/fs8y/qsq8tcTOu9bDyc + Platform + platform/bOjudix1aOpCirU2sO/Platform + platform/C0ru0zr + platform/Isum/tNPQw7vT0M/Platform + platform = "brush: java; "> public class DownloadUt Ils {// completed thread private int completeThread; private int threadCount; /*** start multi-thread download ** @ param url * server address accessed * @ param dir * local receiving path * @ param threadCount * How many threads are enabled to download */public void startMultiThreadDownload (final String url, final String dir, final int threadCount) {this. threadCount = threadCount; completeThread = 0; new Thread (new Runnable () {@ Overridepublic void run () {// 1. length of the file on the request server int fileLength = getR EmoteServiceFileLength (url); if (fileLength =-1) {System. out. println ("failed to request Server File length, stop downloading"); return;} System. out. println ("the length of the remote server is:" + fileLength); // 2. create an identical file String fileName = url on the mobile phone based on the file length on the server. substring (url. lastIndexOf ("/") + 1); File file = new File (dir, fileName); try {RandomAccessFile raf = new RandomAccessFile (file, "rwd"); raf. setLength (fileLength); raf. close (); System. out. println ("local file created successfully" + File. getPath ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} // 3. calculate the download range of each thread based on the number of threads and the length of the file. int blockSize = fileLength/threadCount; for (int I = 0; I <threadCount; I ++) {// start position: the size of each thread id. Int start = I * blockSize; // end position: thread (id + 1) * size of each block-1; int end = (I + 1) * blockSize-1; // The end position of the last thread is: file length-1; if (I = threadCount-1) {end = fileLength-1 ;} // 4. enable multiple threads, and each thread downloads its own range, passing parameters: the path of the stored file // start position, end position, thread IDnew Thread (new DownloadRunnable (url, file. getPath (), start, end, I )). start ();}}}). start ();}/*** download task class ** @ author Administrator **/class DownloadRunnable implements Runnable {Private String url; private File localFile; // File path private int start; // the location where the current thread starts to download private int end; // the location where the download ends private int threadID; // thread IDpublic DownloadRunnable (String url, String path, int start, int end, int I) {this. url = url; this. localFile = new File (path); this. start = start; this. end = end; this. threadID = I ;}@ Overridepublic void run () {HttpURLConnection conn = null; try {// Add breakpoint download int total = 0; // The total download progress of the current thread // store the total progress value locally to File cacheFile = new File (localFile. getParent (), "thread" + threadID + ". hm "); RandomAccessFile cacheRAF = new RandomAccessFile (cacheFile," rwd "); // you can determine whether a cache progress exists. if (cacheFile. exists () & cacheFile. length ()> 0) {// The object exists and has data // The last download progress int progress = Integer. valueOf (cacheRAF. readLine (); start + = progress; // Add the last progress to the start position and continue to download total = progress; // assign a value to the previous download progress} System. out. pri Ntln ("Thread" + threadID + ", started to download. The download range is:" + start + "~ "+ End); conn = (HttpURLConnection) new URL (url ). openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); conn. setReadTimeout (5000); // sets the request header message: Range, which is part of the content conn of the file on the request server. setRequestProperty ("Range", "bytes =" + start + "-" + end); int responseCode = conn. getResponseCode (); if (responseCode = 206) {int contentLength = conn. getContentLength (); System. out. println ("Thread" + threadID + ", request successful, content Length: "+ contentLength); // obtain the data returned by the server. InputStream is = conn. getInputStream (); RandomAccessFile raf = new RandomAccessFile (localFile, "rwd"); // move the write position to the starting position of the thread. seek (start); byte [] buf = new byte [1024]; int len = 0; while (len = is. read (buf ))! =-1) {raf. write (buf, 0, len); total + = len; cacheRAF. seek (0); // each time it is moved to the starting position of the file to write cacheRAF. write (String. valueOf (total ). getBytes ();} cacheRAF. close (); raf. close (); is. close (); System. out. println ("Thread" + threadID + ", download complete. "); completeThread ++; if (completeThread = threadCount) {System. out. println ("Download all complete. Delete the temporary configuration file. "); for (int I = 0; I <threadCount; I ++) {File deleteFile = new File (localFile. getParent (), "t Hread "+ I + ". hm "); System. out. println (deleteFile. delete () ;}}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (conn! = Null) {conn. disconnect ();}}}} /*** request the remote server to obtain the file size based on the URL ** @ param url * server address * @ return */private int getRemoteServiceFileLength (String url) {HttpURLConnection conn = null; try {conn = (HttpURLConnection) new URL (url ). openConnection (); // request method, which must be conn. setRequestMethod ("GET"); // connection timeout conn. setConnectTimeout (5000); // read timeout conn. setReadTimeout (5000); int reponseCode = conn. getResponseCode (); // the response of the server Response code if (reponseCode = 200) {return conn. getContentLength () ;}} catch (Exception e) {e. printStackTrace () ;}finally {if (conn! = Null) {conn. disconnect () ;}} return-1 ;}}

Call:

Public class Demo {public static void main (String [] args) {System. out. println ("multi-threaded download ............ "); // link, path, number of threads String url =" http: // 192.168.1.109/FeiQ.exe "; String dir =" F:/WDJDownload "; int threadCount = 3; downloadUtils du = new DownloadUtils (); du. startMultiThreadDownload (url, dir, threadCount );}}

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.