码迷,mamicode.com
首页 > 编程语言 > 详细

多线程断点下载

时间:2015-11-19 12:50:41      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

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


public class MultiDownload {
    long beginTime;
    int threadCount;
    int runningThread;
    int fileSize;
    FileLog fileLog = null;

    public MultiDownload(int threadCount, FileLog fileLog) {
        this.beginTime = System.currentTimeMillis();
        this.threadCount = threadCount;
        this.runningThread = threadCount;
        this.fileLog = fileLog;
    }

    public void multiThreadDownload(String sourcePath, File targetFile) {
        fileSize = getFileSize(sourcePath);
        int blockSize = fileSize / threadCount;
        System.out.println("blockSize=" + blockSize);
        for (int threadId = 1; threadId <= threadCount; threadId++) {
            int beginIndex = (threadId - 1) * blockSize;
            int endIndex = threadId * blockSize - 1;
            if (threadId == threadCount) {
                endIndex = fileSize - 1;
            }
            System.out.println("thread=" + threadId + " " + beginIndex + " -- " + endIndex);
            if (!targetFile.getParentFile().exists())
                targetFile.getParentFile().mkdirs();
            if (!targetFile.exists())
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            new DownloadThread(threadId, sourcePath, beginIndex, endIndex, targetFile).start();
        }
    }

    public class DownloadThread extends Thread {
        private String sourcePath;
        private int beginIndex;
        private int endIndex;
        private int threadId;
        private File targetFile;

        public DownloadThread(int threadId, String sourcePath, int beginIndex, int endIndex, File targetFile) {
            this.sourcePath = sourcePath;
            this.beginIndex = beginIndex;
            this.endIndex = endIndex;
            this.threadId = threadId;
            this.targetFile = targetFile;
        }

        @Override
        public void run() {
            HttpURLConnection conn = null;
            RandomAccessFile raf;

            try {
                raf = new RandomAccessFile(targetFile, "rwd");
                URL url = new URL(sourcePath);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(10000);
                if (fileLog.getAlreadyData(threadId) != -1)
                    beginIndex = fileLog.getAlreadyData(threadId);
                conn.setRequestProperty("Range", "bytes=" + beginIndex + "-" + endIndex);
                int code = conn.getResponseCode();
                int total = 0;
                if (code == 206) {
                    InputStream is = conn.getInputStream();
                    raf.seek(beginIndex);
                    int len;
                    byte[] buff = new byte[1024];
                    while ((len = is.read(buff)) != -1) {
                        raf.write(buff, 0, len);
                        total += len;
                        fileLog.set(String.valueOf(threadId), total + beginIndex - 1 + "");
                        //System.out.println("线程" + threadId + " 开始下载=" + String.valueOf(total + beginIndex - 1));
                    }
                }
                runningThread--;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (runningThread == 0) {
                    long endTime = System.currentTimeMillis();
                    long time = (endTime - beginTime) / 1000;
                    double speed = (double) fileSize / 1024 / 1024 / time;

                    System.out.println("下载完成用时" + time + "秒" + " " + Math.ceil(speed * 100) / 100 + "MB/S");
                    fileLog.deleteFile();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }
    }

    private static int getFileSize(String sourcePath) {
        int fileSize = 0;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(sourcePath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            int code = conn.getResponseCode();
            if (code == 200) {
                fileSize = conn.getContentLength();
                double d = fileSize / 1024 / 1024;
                System.out.println("文件总大小=" + Math.ceil(d * 100) / 100 + "MB");
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return fileSize;
    }
}
import java.io.*;
import java.util.*;

public class FileLog {
    Properties properties = new Properties();
    File file;
    public FileLog(File file) {
        this.file = file;
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    public synchronized void set(String key,String value) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(file);

            properties.load(is);
            Enumeration e = properties.propertyNames();
            while (e.hasMoreElements()) {
                String mKey = (String) e.nextElement();
                String mValue = properties.getProperty(mKey);
                if (mKey.equals(key)) {
                    properties.setProperty(key, value);
                } else {
                    properties.setProperty(mKey, mValue);
                }
            }
            properties.setProperty(key, value);
            is.close();
            os = new FileOutputStream(file);
            properties.store(os, "");
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String get(String key) {
        String value = null;
        try {
            InputStream is = new FileInputStream(file);
            properties.load(is);
            value = properties.getProperty(key);
            System.out.println("FileLog get() "+"key="+key + " "+"value="+value);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
    public int getAlreadyData(int key){
        int data = -1;
        if (file.exists()&& file.length()>0) {
            String value = get(String.valueOf(key));
            if (value != null)
                data = Integer.parseInt(value);
        }
        return data;
    }
    public void getAll(){
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            properties.load(is);
            Enumeration e = properties.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = properties.getProperty(key);
                //System.out.println(key+" "+value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void deleteFile() {
        file.delete();
    }

}
        String targetPathDir = "z:\\";
        String targetFileName = "setup.exe";
        String sourcePath = "http://down.360safe.com/setup.exe";
       
        File targetFile = new File(targetPathDir, targetFileName);
        FileLog fileLog = new FileLog(new File(targetPathDir, targetFileName.substring(0,targetFileName.indexOf(‘.‘)) + ".txt"));
        MultiDownload multiDownload = new MultiDownload(2, fileLog);
        multiDownload.multiThreadDownload(sourcePath, targetFile);

 

多线程断点下载

标签:

原文地址:http://www.cnblogs.com/linson0116/p/4977235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!