import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MulDownloadMain {
public static void main(String[] args) throws Exception{
//目标文件地址(这里以有道词典为例进行下载)
String downpath = "http://codown.youdao.com/cidian/YoudaoDict_youdao.fanyiindex.exe";
//下载后保存的位置
String filepath = "d:"+File.separator+"YoudaoDict_youdao.fanyiindex.exe";
//线程数
int threadCount = 5;
URL url = new URL(downpath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
//服务器端返回的数据的长度,实际上就是文件的长度
int fileLength = conn.getContentLength();
System.out.println("文件总长度:"+fileLength);
//在客户端本地创建出来一个大小跟服务器端一样大小的临时文件
RandomAccessFile raf = new RandomAccessFile(filepath, "rwd");
//指定创建的这个文件的长度
raf.setLength(fileLength);
raf.close();
//假设是5个线程去下载资源,平均每一个线程下载的文件大小.
int blockSize = 0;
if (fileLength % threadCount == 0) {
blockSize = fileLength / threadCount;
} else {
blockSize = fileLength / threadCount +1;
}
//开启子线程进行下载
for (int i = 0; i < threadCount; i++) {
System.out.println("线程:"+i+"下载");
new DownLoadThread(i,blockSize,filepath,downpath).start();
}
}
}
}
package com.demo;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadThread extends Thread{
private int threadId; //线程id
private String filepath;//文件保存路径
private String downpath;//目标文件的地址
private int startIndex;//下载的开始位置
private int endIndex;//下载的结束位置
/**
*
* @param threadId 线程id
* @param blockSize 每个子线程将要下载的大小
* @param filepath 目标文件的路径
* @param downpath 文件保存路径
*/
public DownLoadThread(int threadId,int blockSize,String filepath,String downpath) {
this.threadId = threadId;
this.filepath = filepath;
this.downpath = downpath;
this.startIndex = threadId * blockSize; //重要:请求服务器下载开始下载位置
this.endIndex = (threadId +1 )* blockSize -1;//重要:请求服务器下载结束位置
}
@Override
public void run() {
try {
URL url = new URL(downpath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//重要:请求服务器下载部分文件 指定文件的位置
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
//此处不用从服务器请求全部资源返回200,再上一个界面已经打开了
InputStream is = conn.getInputStream();//已经设置了请求的位置,返回的是当前位置对应的文件的输入流
RandomAccessFile raf = new RandomAccessFile(filepath, "rwd");
//随机写文件的时候从哪个位置开始写
raf.seek(startIndex);//定位文件
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
raf.write(buffer, 0, len);
}
is.close();
raf.close();
System.out.println("线程:"+threadId+"下载完毕");
} catch (Exception e) {
e.printStackTrace();
}
}
}