JAVA uses multiple threads to download resources from the server

Source: Internet
Author: User

JAVA uses multiple threads to download resources from the server

In Android, resumable download and upload are all based on JAVA breakpoints. Generally, databases and multithreading are used for breakpoints. The database is used to instantly save the download progress of each thread, that is, their download status, while multithreading is used to download files simultaneously.

Here we will share with you the multi‑thread download function. JAVA version.

General idea: first, we need to clearly know that the downloaded resource path is located on the server, which can be a direct path or Servlet, and then we can download it through multiple threads. Because you need to operate a file at the same time, you need to use a file class named RandomAccessFile, which contains a seek () method that allows you to move the pointer to a certain position of the file and start reading. But what we need is instant reading, that is, I have read a bit from the network, and I want to update it in the file, instead of storing the resources read from the network in the memory, the read is completed in the file, which helps improve performance. So let's take a look at a diagram of the constructor method of this class: (the API is 6.0)

That's right. We need to set the mode to the "rwd" mode to meet the requirements.

Read the code in detail:

 

/*** Multi‑thread breakpoint download using JAVA ** @ author Li Weijie * @ version 1.0 */public class MulThreadDownload {public static void main (String [] args) {/* the path of the file to be downloaded on the server can be the resource path or Servlet path. This is the actual path */String path = "http: // 192.168.1.135: 8080/web/Lenovo.exe "; try {new MulThreadDownload (). download (path, 3); // three threads are used to download this file. Generally, too many threads are not suitable, otherwise, the System may kill some threads} catch (Exception e) {System. out. println ("Download failed"); e. printStackTrace ();}}/** * Download file ** @ param path network file path * @ throws Exception */private void download (String path, int threadSize) throws Exception {URL url = new URL (path ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {int length = conn. getContentLength (); File file = new File (getFileName (path);/** generate a File equal to the network file in bytes., Rwd indicates: * It is enabled for reading and writing. For "rw", it also requires that each update of the file content be synchronized to the underlying storage device. * The data can be updated every time it is read, which ensures the accuracy of calculating the downloaded length. */RandomAccessFile accessFile = new RandomAccessFile (file, "rwd"); accessFile. setLength (length); // generate a local file accessFile with the downloaded file size. close (); int bolck = length % threadSize = 0? Length/threadSize: length/threadSize + 1; // calculate the download quantity of each thread for (int threadid = 0; threadid <threadSize; threadid ++) {new DownloadThread (threadid, bolck, url, file ). start (); // start each thread} else {System. out. println ("Download failed");}/*** subthread for downloading the file * @ author Administrator **/class DownloadThread extends Thread {int threadid; // Thread id 0, 1, 2int bolck; // URL of the downloaded size; // download path File; // the local file downloaded to public DownloadThread (int Threadid, int bolck, URL url, File file) {this. threadid = threadid; this. bolck = bolck; this. url = url; this. file = file ;}@ Overridepublic void run () {int start = threadid * bolck; // calculate the start position of each thread, int end = (threadid + 1) * bolck-1; try {RandomAccessFile accessFile = new RandomAccessFile (file, "rwd"); accessFile. seek (start); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // HTTP protocol G is used here ET Method, where the range header field can be used for breakpoint, the starting position and ending position of each thread conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); conn. setRequestProperty ("range", "bytes =" + start + "-" + end); if (conn. getResponseCode () == 206) {InputStream is = conn. getInputStream (); byte [] B = new byte [1024]; int len; while (len = is. read (B ))! =-1) {accessFile. write (B, 0, len);} accessFile. close (); is. close (); System. out. println ("no." + (threadid + 1) + "thread download completed") ;}} catch (Exception e) {System. out. println (threadid + "failed to download part of thread") ;}} private static String getFileName (String path) {return path. substring (path. lastIndexOf ("/") + 1 ));}}

In this way, a multi-threaded download can be completed.

 

 

 

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.