JAVA多线程下载

package bean;


import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;


import java.net.URL;


public class Demo_threadload {


public static void main(String[] args) throws Exception {
//要下载的文件地址 我这里是网上找的一张图片

String path="http://image.xinmin.cn/2013/03/18/20130318070117480093.jpg";

new Demo_threadload().download(path, 3);
}

private String getFileName(String path){
return path.substring(path.lastIndexOf("/")+1);
}
private void download(String path,int threadsize) throws Exception{
URL url=new URL(path);
//使用jdk自带的httpURLConnection 向url发送请求并输出结果
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//传输方式设置
connection.setRequestMethod("GET");
//连接超时设置
connection.setConnectTimeout(20000);
/*
* http请求有一个状态码
* 200成功连接服务器
* 4xx客户端错误
* 5xx服务器有问题
* */
if(connection.getResponseCode()==200){
//获取文件长度
int length=connection.getContentLength();
//本地文件
File file=new File(getFileName(path));
//在本地生成一个长度与下载文件相同的文件
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("连接超时");
}

}
//线程类
private class downloadthread extends Thread{
private int block;
private URL url;
private File file;
private int threadid;
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);//start指针发生改变
//使用jdk自带的httpURLConnection 向url发送请求并输出结果
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//传输方式设置
connection.setRequestMethod("GET");
//连接超时设置
connection.setConnectTimeout(20000);
//range
connection.setRequestProperty("Range", "bytes="+start+"-"+end);
//注意多线程下载的状态码是206
if(connection.getResponseCode()==206){
//流将要下载的内容 存入自己的硬盘上
InputStream inputStream=connection.getInputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=inputStream.read(buffer))!=-1){
//将流写到硬盘上
accessfile.write(buffer,0,len);
}
accessfile.close();
inputStream.close();
}
System.out.println("第"+(threadid+1)+"条线程已经下载完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值