package com.zkq.dowload;
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://192.168.1.186:8080/web/setup_8.8.0.2001b.exe";
new MulThreadDownload().download(path,3);
}
/**
* 下载
* @param path网络文件地址
* @param threadsize线程数
* @throws Exception
*/
private 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();//获取网络文件的长度
String filename=getFileName(path);
//可以在这里设置文件的保存路径 如:"d:/data/"+filename
File file=new File(filename);
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("下载失败");
}
}
/**
* 获取文件名称
* @param path
* @return
*/
private String getFileName(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
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();
}
}
}
}