日期:2014-05-20 浏览次数:20711 次
public class MulThreadDownLoadTest {
private File file ;
public static void main(String args []) throws Exception{
String path = "http://localhost:8080/test/chrome.exe";
new MulThreadDownLoadTest().download(path,3);
}
public void download(String path, int threadCount ) throws Exception{
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(500);
if(con.getResponseCode() == 200){
String fileName = getFileName(path); //获取文件名
file = new File(fileName);
int ContentLength = con.getContentLength();//获取响应的长度
System.out.println("下载文件大小"+ContentLength);
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");
accessFile.setLength(ContentLength);
//计算每个线程的下载长度为多少
int tasksize = (ContentLength%threadCount == 0 ? ContentLength/threadCount : ContentLength/threadCount+ 1);
accessFile.close();
for(int threadid = 0; threadid < threadCount ;threadid++ ){
new MulThreadDownLoad(path,file,tasksize,threadid).start();
}
}
}
public static String getFileName(String path){
return path.substring(path.lastIndexOf("/")+1);
}
}
public class MulThreadDownLoad extends Thread {
private String path;
private File file;
private int tasksize;
private int threadid;
public MulThreadDownLoad(String path ,File file , int tasksize, int threadid){
this.path = path; //文件路径
this.file = file; //文件
this.tasksize = tasksize; //线程的下载量
this.threadid = threadid; //线程的id
}
@Override
public void run() {
try {
int startPoint = threadid * tasksize; //每条线程写入文件的起点
int endPoint = (threadid + 1 ) * tasksize -1 ; //每条线程写入文件的终点
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");
accessFile.seek(startPoint);
HttpURLConnection con = (HttpURLConnection) new URL(path).openConnection();
con.setConnectTimeout(500);
con.setRequestMethod("GET");
con.setRequestProperty("Range", "bytes = "+startPoint+"-"+endPoint);
if(con.getResponseCode() == 206){
InputStream ins = con.getInputStream();
byte [] buffer = new byte [1024];
int length = 0;
while((length = ins.read(buffer)) != -1 ){ //将读取的字节写入文件中
accessFile.write(buffer, 0, length);
}
accessFile.close();
ins.close();
}
System.out.print((threadid +1 )+"线程已经下载完成 :");