package com.test.download;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MulThreadDownload {
public static void main(String[] args) throws Exception {
String path = "http://pic.4j4j.cn/upload/pic/20130909/681ebf9d64.jpg";
new MulThreadDownload().download(path,3);
}
public void download (String path,int threadsize) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
int length = conn.getContentLength();
File file = new File(getFilename(path));
int block = length%threadsize==0 ? length/threadsize : length/threadsize+1;
for(int threadid = 0; threadid < threadsize; threadid++){
new DownloadThread(threadid,block,url,file).start();
}
}else{
System.out.println("下载失败!");
}
}
private class DownloadThread extends Thread{
private int threadid;
private int block;
private URL url;
private File file;
public DownloadThread(int threadid, int block, URL url, File file) {
this.threadid = threadid;
this.block = block;
this.url = url;
this.file = file;
}
public void run() {
int start = threadid * block;
int end = (threadid+1) * block - 1;
try {
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.seek(start);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
if(conn.getResponseCode() == 206){
InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) != -1){
accessFile.write(buffer, 0, len);
}
accessFile.close();
inStream.close();
}
System.out.println("第"+(threadid+1)+"部分下载完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getFilename(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
}