Android learning history (5)-learning multi-thread download in java-resumable download ②

Source: Internet
Author: User
Tags file url

In the previous section, we learned the basic principles and usage of multi-threaded download in java. We didn't talk about multithreaded resumable upload, next we will talk about resumable data transfer in this section. The importance of resumable data transfer is self-evident. You can save time without having to download it again, the key to resumable download is how to record the download progress and how to identify it. Let's talk about it now.

Simply put, a file is opened for each thread to record the download progress of each thread, and the mark file exists before each thread downloads, if the data in the corresponding file is read, set the download thread to the corresponding download point.

The code in this section is similar to the Code in the previous section. It is just a piece of code that marks the download progress. Now let's take a look.

This code is used to determine whether the file with the download progress recorded by each thread exists in the download thread. If so, read the progress in the thread. Set the value of startIndex to the corresponding data.

Then, how is the file marked with the download progress generated? Where is the file generated? The Code is as follows:

This record file is generated when the downloaded file is written to the local device.

The last step is to delete the file that marks the download progress of each thread after all threads are completed. Remember: it is true that all threads are deleted after the end, not after each download thread is completed. Why are all threads deleted after completion? I will not explain it for myself! <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.bkjia.com/uploadfile/Collfiles/20140104/20140104132929233.jpg" alt = "\">

This is the operation to delete the Tag file. The explanation here is complete. Do you understand?

Now I will post the complete code and share it with you. The Code is as follows:

Package net. loonggg. test; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL; public class MutilDownloader {// Number of threads enabled public static final int THREAD_COUNT = 3; public static int runningThread = 3; // record the number of running download file threads public static void main (String [] args) throws Exception {String path = "file "; // 1. Connect to the server, get a file, get the file length, and create a local Temporary File URL with the same size as the Server File url = new URL (path ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); int code = conn. getResponseCode (); if (code = 200) {// The length of the data returned by the server, which is actually the object length int length = conn. getContentLength (); System. out. println ("---- total file length ----" + length); // create a temporary file named RandomAcces that is the same size as the Server File locally on the client. SFile raf = new RandomAccessFile ("temp.apk", "rwd"); // specify the length of the created file. setLength (length); // disable rafraf. close (); // assume three threads are used to download resources. // The average file size of each thread is int blockSize = length/THREAD_COUNT; for (int threadId = 1; threadId <= THREAD_COUNT; threadId ++) {// the position where the first thread starts to download int startIndex = (threadId-1) * blockSize; int endIndex = threadId * blockSize-1; if (threadId = THREAD_COUNT) {endIndex = length;} System. ou T. println ("---- threadId ---" + "-- startIndex --" + startIndex + "-- endIndex --" + endIndex); new DownloadThread (path, threadId, startIndex, endIndex ). start () ;}}/ *** subthread for downloading an object, each Thread downloads the file ** @ author loonggg **/public static class DownloadThread extends Thread {private int threadId; private int startIndex; private int endIndex; private String path; /*** @ param path * path of the downloaded file on the server * @ param threadId * Line Thread id * @ param startIndex * start position of thread download * @ param endIndex * end position of thread download */public DownloadThread (String path, int threadId, int startIndex, int endIndex) {this. path = path; this. threadId = threadId; this. startIndex = startIndex; this. endIndex = endIndex ;}@ Overridepublic void run () {try {// check whether a file with a download length record exists, if there is data File tempFile = new File (threadId + ". txt "); if (tempFile. exists () & tempFile. length ()> 0) {FileInputStream FCM = new FileInputStream (tempFile); byte [] temp = new byte [1024*10]; int leng = Fi. read (temp); // The downloaded length String downloadLen = new String (temp, 0, leng); int downloadInt = Integer. parseInt (downloadLen); startIndex = downloadInt; FCM. close () ;}url URL = new url (path); HttpURLConnection conn = (HttpURLConnection) URL. openConnection (); conn. setRequestMethod ("GET"); // important: Requests the server to download the specified file Location conn. setRequestProperty ("Range", "bytes =" + startIndex + "-" + endIndex); conn. setConnectTimeout (5000); // status code of the slave server requesting all resources 200 OK if the status code of some resources requested by the slave server is 206 okint code = conn. getResponseCode (); System. out. println ("--- code ---" + code); InputStream is = conn. getInputStream (); // The request location has been set. The returned result is the input stream RandomAccessFile raf = new RandomAccessFile ("temp.apk", "rwd") of the file corresponding to the current location "); // The position where the random write operation starts to write the raf file. seek (startIndex); // set Bit file int len = 0; byte [] buffer = new byte [1024]; int total = 0; // record the length of downloaded data while (len = is. read (buffer ))! =-1) {RandomAccessFile recordFile = new RandomAccessFile (threadId + ". txt "," rwd "); // record the download progress of each thread and Mark raf for resumable upload. write (buffer, 0, len); total + = len; recordFile. write (String. valueOf (startIndex + total ). getBytes (); recordFile. close ();} is. close (); raf. close (); System. out. println ("thread:" + threadId + "Download complete! ");} Catch (Exception e) {e. printStackTrace () ;}finally {runningThread --; if (runningThread = 0) {// All threads have been executed for (int I = 1; I <= THREAD_COUNT; I ++) {File file = new File (I + ". txt "); file. delete ();}}}}}}


Related Article

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.