多线程下载

public class DownLoad {
public static String path = "http://192.168.0.101:8080/11.mp4";//服务器地址,
public static void main(String[] args) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
conn.setRequestProperty("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");//浏览器方式下载
if (conn.getResponseCode() == 200) {
int len = conn.getContentLength();

RandomAccessFile file = new RandomAccessFile(getFileName(path), "rwd");// RandomAccessFile此类可以指定从文件哪个部位操作 ,有.seek()方法。

file.setLength(len);//设置本地文件大小与服务器文件的大小一样
int threadnumber = 3;//设置线程为3 个
int blocksize = len / threadnumber;//每个线程下载的大小

for (int i = 0; i < threadnumber; i++) {
int startfile = i * blocksize;
int endfile = (i + 1) * blocksize;
if (i == (threadnumber - 1)) {     //最后一个线程下载的就是剩余的所有
endfile = len;
}
DownLoadTask task = new DownLoadTask(i, path, startfile, endfile);
task.start();
}
}
}
public static String getFileName(String path) {
int start = path.lastIndexOf("/") + 1;//根据/拆分pant取得最后一个/后面第一个字符所在位置
return path.substring(start, path.length());//得到最后一个/后面的所有内容
}
}

class DownLoadTask extends Thread {
int threadid;
String filepath;
int startfile;
int endfile;
public static String path = "http://192.168.0.101:8080/11.mp4";
public static String getFileName(String path) {
int start = path.lastIndexOf("/") + 1;
return path.substring(start, path.length());

}
public DownLoadTask(int threadid, String filepath, int startfile, int endfile) {
super();
this.threadid = threadid;
this.filepath = filepath;
this.startfile = startfile;
this.endfile = endfile;
}
public void run() {
try {
URL url = new URL(filepath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes=" + startfile + "-" + endfile);//设置请求的文件位置的开始与结束。
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
InputStream is = conn.getInputStream();
RandomAccessFile file = new RandomAccessFile(getFileName(path), "rwd");
file.seek(startfile);//设置从文件哪个地方开始
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
file.write(buffer, 0, len);
}
file.close();
System.out.println("线程" + threadid + "下载完成");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

最后值得注意是下载完之后要刷新工程才能看到工程中有下载的文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值