Android核心技术-day05-04-JavaSE多线程下载

package com.gaozewen.lib;

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 MultiDownloader {
    public static final String path = "http://192.168.1.102:8080/xunlei.exe";
    public static final int TOTAL_THREAD_COUNT = 3;
    public static int runningThreadCount = 0;

    public static void main(String[] args) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            if (code == 200) {
                int length = conn.getContentLength();
                System.out.println("file length: " + length);
                // 创建一个空的文件,并且设置他的文件长度等于服务器上的文件长度
                RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw");
                raf.setLength(length);
                raf.close();

                int blockSize = length / TOTAL_THREAD_COUNT;
                System.out.println("every block size: " + blockSize);
                runningThreadCount = TOTAL_THREAD_COUNT;
                for (int threadId = 0; threadId < TOTAL_THREAD_COUNT; threadId++) {
                    int startPosition = blockSize * threadId;
                    int endPosition = blockSize * (threadId + 1) - 1; // -1 是到当前块的最后一个字节
                    if (threadId == (TOTAL_THREAD_COUNT - 1)) {
                        endPosition = length - 1;
                    }
                    System.out.println(String.format("threadId: %s\ndownload rage: %s to %s", threadId, startPosition, endPosition));

                    new DownloadThread(threadId, startPosition, endPosition).start();
                }
            } else {

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从网路路径获取文件名
     *
     * @param path 网络路径
     * @return 文件名
     */
    private static String getDownloadFileName(String path) {
        return path.substring(path.lastIndexOf("/") + 1);
    }

    /**
     * 下载文件的线程
     */
    private static class DownloadThread extends Thread {
        /**
         * 线程 id
         */
        private int threadId;
        /**
         * 当前线程下载的起始位置
         */
        private int startPosition;
        /**
         * 当前线程下载的终止位置
         */
        private int endPosition;

        public DownloadThread(int threadId, int startPosition, int endPosition) {
            this.threadId = threadId;
            this.startPosition = startPosition;
            this.endPosition = endPosition;
        }

        @Override
        public void run() {
            System.out.println(String.format("threadID: %s  begin working", threadId));
            // lest thread download it's self range data
            try {
                // 查询 记录断点信息的文件
                File finfo = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt");
                if (finfo.exists() && finfo.length() > 0) { // 断点下载
                    FileInputStream fis = new FileInputStream(finfo);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    String lastPosition = br.readLine();
                    // This thread download data before times;
                    startPosition = Integer.parseInt(lastPosition);
                    fis.close();
                }
                // 第一次下载
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                System.out.println(String.format("begin and end: %s  range of download: %s to %s", threadId, startPosition, endPosition));
                conn.setRequestProperty("Range", String.format("bytes=%s-%s", startPosition, endPosition));
                // 从服务器下载资源
                int code = conn.getResponseCode();
                if (code == 206) {
                    InputStream is = conn.getInputStream();
                    // 第一次没有这个文件则创建,下次直接打开这个文件
                    RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw");
                    // !!! position of begin to write
                    raf.seek(startPosition);
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    int total = 0; // 当前线程 这次下载的数据
                    while ((len = is.read(buffer)) != -1) {
                        raf.write(buffer,0,len);
                        total += len;
                        // 创建记录 保存当前线程下载的位置 (注意: rwd 同步实时写入到设备中)
                        RandomAccessFile infoRaf = new RandomAccessFile(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt","rwd");
                        infoRaf.write(String.valueOf(startPosition + total).getBytes());
                        infoRaf.close();
                    }
                    raf.close();
                    is.close();
                    System.out.println(String.format("thread: %s  download complete...",threadId));
                }else {
                    System.out.println("request download failed");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                synchronized (MultiDownloader.class){
                    runningThreadCount--;
                    if(runningThreadCount <= 0){ // 多线程下载完成 删除 位置信息文件
                        System.out.println("multi thread download complete.");
                        for (int i = 0; i < TOTAL_THREAD_COUNT; i++) {
                            File positionFile = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + i + ".txt");
//                            System.out.println(positionFile.delete());
                        }
                    }
                }
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值