package cn.com.download;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MulThreadDownload {
/**
* @param args
* @throws MalformedURLException
*/
public static void main(String[] args) throws Exception {
String path = "http://abdl.baofeng.com/actions/storm_715.exe";
new MulThreadDownload().download(path,3);
}
/**
* 下载文件
* @param path 网络文件路径
* @throws MalformedURLException
*/
private void download(String path,int threadsize) throws Exception {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()==200){//下载的connection.getResponseCode()==206
//得到网络文件的长度
int length = connection.getContentLength();
//生成一个与网络文件长度相同的文件
File file = new File(getFilename(path));
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
//设置生成的文件长度
accessFile.setLength(length);
accessFile.close();
//计算每个进程负责下载 的数据量
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 connection =(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Range","bytes="+start+"-"+end);
if(connection.getResponseCode()==206){
InputStream inputStream = connection.getInputStream();
byte[]buffer=new byte[1024];
int len = 0;
while((len=inputStream.read(buffer))!=-1){
accessFile.write(buffer,0,len);
}
accessFile.close();
inputStream.close();
}
System.out.println("第"+(threadid+1)+"条线程已经下载完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获得网络文件名称
* @param path
* @return
*/
private String getFilename(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
}