博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
myUtils-多线程下载
阅读量:4290 次
发布时间:2019-05-27

本文共 2077 字,大约阅读时间需要 6 分钟。

int threadCount=3;
String url_st = "http://192.168.11.60:8080/mytry/FilePush?file=122.PNG";
String file_path = "D:/zhang.png";
//连接网络,获得文件大小。
URL url = new URL(url_st);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(10000);
int status = http.getResponseCode();
if(status == 200){
int len = http.getContentLength();
//设置存储的位置
File file = new File(file_path);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
//设置缓存文件大小。充大内容。
raf.setLength(len);
raf.close();
int blocksize = len/threadCount;
for(int i=0;i<threadCount;i++){
//按照数组的序号
int start=i*blocksize;
int end = (i+1)*blocksize-1;
if(i == (threadCount-1)){
end = len-1;
}
System.out.println("需要下载大小:"+len);
new Thread(new MyRunnable(url_st,file_path,start,end)).start();
}
}else{
//网络错误响应
}
class MyRunnable implements Runnable{
private String url_st;
private String file_path;
private int start;
private int end;
public MyRunnable(String url_st, String file_path, int start, int end) {
this.url_st = url_st;
this.file_path = file_path;
this.start = start;
this.end = end;
System.out.println(">>>>>>>>>开启一个新的线程。start:"+start+" end:"+end);
}
@Override
public void run() {
try {
URL url = new URL(url_st);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Range", "bytes="+start+"-"+end);
http.setConnectTimeout(10000);
//开始写
InputStream is = http.getInputStream();
RandomAccessFile raf = new RandomAccessFile(file_path,"rwd");
raf.seek(start);
byte[] buffer = new byte[1024*10];
int len =0;
while((len = is.read(buffer)) != -1){
raf.write(buffer, 0, len);
//标记写的位置,可以用来续传
}
raf.close();
http.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
// 客户端进行 Range 网络请求,或者进行接收的 skip
输入流的: skip(long bytes);//由于skip不稳定,一般不直接使用
public static void skipFully(InputStream is,long bytes) throws IOException{
long remaining = bytes;
long len = 0;
while(remaining > 0){
len = is.skip(remaining);
remaining -= len;
}
}

转载地址:http://xbegi.baihongyu.com/

你可能感兴趣的文章
架构师之路--视频业务介绍,离线服务架构和各种集群原理(1/2)
查看>>
一台nginx服务器多域名配置
查看>>
关于java web项目使用log4j / 当装了两个tomcat后,如何修改tomcat端口
查看>>
大数据和高并发的解决方案汇总
查看>>
Mysql索引会失效的几种情况分析
查看>>
使用redis实现消息发布订阅
查看>>
数据库性能优化的五种方案(mycat,基于阿里coba开源的数据库中间件,很容易实现分库分表、主从切换功能。另一个当当网开源的一个库 sharding-jdbc)
查看>>
Java NIO详解
查看>>
Mycat分库分表的简单实践 / 用Mycat,学会数据库读写分离、分表分库
查看>>
MySQL索引实战汇总
查看>>
使用ssh在远程linux服务器上安装oracle
查看>>
spring的xml中注册bean的时候报错1) 无法找到文档; 2) 无法读取文档; 3) 文档的根元素不是 <xsd:schema>
查看>>
连接Linux服务器操作Oracle数据库
查看>>
mongodb 误删除集合恢复 误删除表数据恢复
查看>>
整理项目改成https访问的操作手册
查看>>
架构必备词汇整理
查看>>
java常见的集合及其关系
查看>>
成为出色的程序员必修之路-数据结构(总结)
查看>>
今天被一个架构师面了
查看>>
java学习建议
查看>>