学习了多线程下载文件
public class DownLoad2 {
/**
* 多线程下载
* */
private static long startTimeMillis = 0; // 开始时间
private long endTimeMillis = 0; // 结束时间
public void down() {
startTimeMillis = System.currentTimeMillis(); // 记录方法开始执行的时间
String url = "http://cyar.118320.com/imports/uploadFile/2016-07-011.xlsx";
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
URL url2=null;
try {
url2 = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client.executeMethod(method);
int length=Integer.valueOf(method.getResponseContentLength()+"");
RandomAccessFile file = new RandomAccessFile("C:/Users/Administrator/Desktop/工作/b.xlsx","rw");//创建一个相同大小的文件。
//7:设置文件大小,占位
file.setLength(length);//设置文件大小。
file.close();
//8:定义线程个数
int size = 3;
//9:计算每一个线程应该下载多少字节的数据,如果正好整除则最好,否则加1
int block = length/size==0?length/size:length/size+1;//计算每个线程应该下载的数据量。
System.err.println("每个线程应该下载:"+block);
for(int i=0;i<size;i++){
int start = i*block;
int end = start+(block-1);//计算每一个线程的开始和结束字节。
System.err.println(i+"="+start+","+end);
new MyDownThread(start, end,url2).start();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
endTimeMillis = System.currentTimeMillis(); // 记录方法执行完成的时间
System.out.println("执行时间:" + (endTimeMillis - startTimeMillis) + "ms;");
}
class MyDownThread extends Thread{
//定义从何地开始下载
private int start;
//定义下载到哪一个字节
private int end;
private URL url;
public MyDownThread(int start,int end,URL url){
this.start=start;
this.end=end;
this.url=url;
}
@Override
public void run() {
try{
//11:开始下载
HttpURLConnection con =
(HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//12:设置分段下载的请求头
con.setRequestProperty("Range","bytes="+start+"-"+end);//设置从服务器上读取的文件块。
//13:开始下载,需要判断206
if(con.getResponseCode()==206){//访问成功,则返回的状态码为206。
InputStream in = con.getInputStream();
//14:声明随机写文件对象,注意rwd是指即时将数据写到文件中,而不使用缓存区
RandomAccessFile out = new RandomAccessFile("C:/Users/Administrator/Desktop/工作/b.xlsx","rwd");
out.seek(start);//设置从文件的某个位置开始写数据。
byte[] b=new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.close();
in.close();
}
System.err.println(this.getName()+"执行完成");
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
DownLoad2 down=new DownLoad2();
down.down();
}
}