稍微改进了下代码
mianqiangsheng opened this issue · comments
mianqiangsheng commented
首先对up主的代码表达敬意,然后我自己小改了下,实现针对特别小的文件下载也支持。修改DownloadMain的splitDownload()方法:
/**
* 切分下载任务到多个线程
*
* @param url
* @param futureList
* @throws IOException
*/
public void splitDownload(String url, List<Future<Boolean>> futureList) throws IOException {
long httpFileContentLength = HttpUtls.getHttpFileContentLength(url);
// 任务切分
long size = httpFileContentLength / DOWNLOAD_THREAD_NUM;
long lastSize = httpFileContentLength - (size * (DOWNLOAD_THREAD_NUM - 1));
/**
* 针对超小的文件,仅启动一个线程来下载
*/
if (size == 0){
DOWNLOAD_THREAD_NUM = 1;
ExecutorService executor = Executors.newFixedThreadPool(DOWNLOAD_THREAD_NUM + 1);
DownloadThread downloadThread = new DownloadThread(url, 0, lastSize, 0, httpFileContentLength);
Future<Boolean> future = executor.submit(downloadThread);
futureList.add(future);
}else {
for (int i = 0; i < DOWNLOAD_THREAD_NUM; i++) {
long start = i * size;
Long downloadWindow = (i == DOWNLOAD_THREAD_NUM - 1) ? lastSize : size;
Long end = start + downloadWindow;
if (start != 0) {
start++;
}
DownloadThread downloadThread = new DownloadThread(url, start, end, i, httpFileContentLength);
Future<Boolean> future = executor.submit(downloadThread);
futureList.add(future);
}
}
}
程序猿阿朗 commented
感谢😀,之前确实没有考虑到文件小到不能切分的情况,代码收下了,后面把这个项目优化下,把小文件逻辑也整合进去哈