首先需要两个类
下载类:
package com.gyx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.*;
public class Download extends Thread{
Integer startIndex;
Integer endIndex;
Integer threadId;
public Download(Integer startIndex, Integer endIndex, Integer threadId) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
try {
//统一资源管理器,可以打开网络地址
URL url = new URL(DownLoadTest.path);
//因为基于http请求,获取HttpURLConnection获取网路连接对象
HttpURLConnection tion = (HttpURLConnection) url.openConnection();
//设置一些参数
tion.setRequestMethod("GET");
//连接超时
tion.setConnectTimeout(5000);
//读取超时
tion.setReadTimeout(5000);
//设置范围 请求参数,获取线程下载范围
tion.setRequestProperty("Range","bytes="+startIndex+"-"+endIndex);
//下载尚未完毕
if (tion.getResponseCode() == 206){
//取出连接中的数据
InputStream in = tion.getInputStream();
//提供一个接收方法
File file = new File("BaiduNetdisk_6.9.7.4.exe");
//输出流 开始写数据 随机写
RandomAccessFile raf = new RandomAccessFile(file,"rwd");
//跳转到每个线程开始的位置
raf.seek(startIndex);
System.out.println("线程:" + threadId + " 开始的位置:" + startIndex + " 结束的位置:" + endIndex);
int len = 0;
byte[] by = new byte[1024];
while ((len = in.read(by)) != -1){
raf.write(by,0,len);
}
System.out.println("线程:" + threadId + "下载完毕");
raf.close();
DownLoadTest.finishadthread++;
//所有线程都下载完毕,让finishesy
synchronized (DownLoadTest.path){
DownLoadTest.finishadthread = 0;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试类
package com.gyx;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadTest {
static String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";
static int threadCount =3;
static int finishadthread = 0;
public static void main(String[] args) throws Exception {
//统一资源管理器 ,可以直接打开 网络地址
URL url = new URL(DownLoadTest.path);
//因为基于http请求 , 获取HttpURLConnection , 获取网络链接对象 ,就可以和服务器建立链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些参数
//get请求
conn.setRequestMethod("GET");
//链接超时
conn.setConnectTimeout(5000);
//读取超时
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200){
//1.拿到文件总长
int len = conn.getContentLength();
//2.每个线程下载的大小
int size = len/threadCount;
//3.开启线程 执行下载
for (int i = 0; i < threadCount; i++) {
int startIndex = i*size;
int endIndex = (i+1)*size; //结束位置
Download thread = new Download(startIndex,endIndex,i);
thread.start();
}
}
}
}
注:尚未实现断点续传功能.