Android多线程断点续传下载原理

步骤:

1.在本地创建一个与服务器端一样大小的空白文件;
确定服务器端文件的大小:发送一个请求,得到content-length;
创建空白文件,设置文件的大小:RandomAccessFile

2.在设置线程的个数;
创建int类型的变量;

3.计算子线程下载数据的范围;
blockSize = length / threadCount;

4.计算子线程下载数据的开始位置和结束位置;
startIndex = threadIdblockSize;
endIndex = (threadId+1)
blockSize-1
最后一个子线程的结束位置:length - 1;
setRequestProperty("Range","bytes=startIndex-endIndex");

5.创建子线程下载数据,设置从哪个位置写数据;
seek();

6.确定文件在什么时间下载完成;
设置一个变量为正在运行的线程的个数,每个子线程下载完成后,都把这个变量-1,当变量为0时表示三个子线程都下载结束了,也表示文件下载完成了;

7.断点续传:实时记录下载到的当前位置,下次下载时,接着上一次下载的位置继续下载;

package com.dominichan.multhreaddownload;

import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiThreadDownload {

    private static String path = "";
    private static int threadCount = 3;

    public static void main(String[] args) {
        //在本地创建一个与服务器一样大小的空白文件
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3000);
            int code = conn.getResponseCode();
            if (code == 200) {
                //得到服务端文件的大小
                int length = conn.getContentLength();
                //在本地创建空白文件并设置大小
                RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");

                //3.计算自线程下载数据的范围
                for (int threadId = 0; threadId < threadCount; threadId++) {
                    int blockSize = length / threadCount;

                    //4计算子线程下载数据的开始位置和结束位置
                    int startIndex = threadId * blockSize;
                    int endIndex = (threadId+1) * blockSize-1;
                    //判断是否是最后一个子线程,确定下载数据的结束位置
                    if (threadCount == threadCount - 1) {
                        endIndex = length - 1;
                    }
                    new ChildThreadDownload(path, startIndex, endIndex, threadId, threadCount).start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.dominichan.multhreaddownload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChildThreadDownload extends Thread{

    private String path;
    private int startIndex;
    private int endIndex;
    private int threadId;
    private int threadCount;
    private static int runningThreadCount;
    public ChildThreadDownload(String path, int startIndex, int endIndex, int threadId, int threadCount) {
        this.path = path;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.threadId = threadId;
        this.threadCount = threadCount;
        this.runningThreadCount = threadCount;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(3000);
            //读取记录下载位置的文件
            File file = new File(threadId+".txt");
            if (file.exists() && file.length() > 0) {

                FileInputStream fis = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                String currentPosition = br.readLine();
                //让子线程从此位置开始下载
                startIndex = Integer.parseInt(currentPosition);
            }
            //告诉服务器只请求这一部分数据
            conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
            int code = conn.getResponseCode();
            System.out.print("线程" + threadId + "开始下载数据");
            if (code == 206) { //206请求部分资源成功返回206
                InputStream is = conn.getInputStream();

                int len = -1;
                byte[] buffer = new byte[1024 * 1024];
                RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");

                //从制定的位置写数据
                raf.seek(startIndex);

                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    raf.write(buffer, 0, len);
                    //计算本次下载的数据大小
                    total += len;
                    //计算当前下载到的位置
                    int currentPosition = startIndex + total;
                    //记录当前下载到的位置
                    RandomAccessFile r = new RandomAccessFile(threadId+".txt","rwd");
                    r.write((currentPosition+"").getBytes());
                    r.close();
                }
                raf.close();
                is.close();
                System.out.print("线程" + threadId + "下载数据完毕...");

                synchronized (ChildThreadDownload.this) {
                    runningThreadCount--;
                    if (runningThreadCount == 0) {
                        System.out.print("文件下载完毕...");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

只是说明了基本原理,抛砖引玉,欢迎各路大神拍砖~

你可能感兴趣的:(Android多线程断点续传下载原理)