android 下载器原理,android多线程下载原理

本文详细介绍了如何利用多线程进行大文件下载,首先通过HttpURLConnection获取网络文件的总长度,然后计算每个线程应下载的数据块,接着开启线程,每个线程负责下载特定范围的数据,并通过设置Range头实现分段下载。最后,线程将数据写入本地文件,实现高效的大文件下载。
摘要由CSDN通过智能技术生成

0818b9ca8b590ca3270a3433284dd417.png

每条线程的下载位置计算:

Intblock = 4;

Intstart = threaid*block;

Int end =(threaid+1)*block-1;

第一步:获取数据总长,生成本地文件

通过观察浏览器返回的数据,可以看到Content-Length字段为数据的总长度

0818b9ca8b590ca3270a3433284dd417.png

调用conn.getContentLength()可以获取数据总长。

获取文件名称:path.substring(path.lastIndexOf("/")+ 1);

path.lastIndexOf("/")取得最后一个"/"的位置编号(从0开始)

path.substring();减去的字符长度

生成本地文件:

RandomAccessFile(file,mode)

0818b9ca8b590ca3270a3433284dd417.png

部分代码:

private voiddownload(String path, int threadsize) throws Exception {

URLdownpath = new URL(path);

HttpURLConnectionconn = (HttpURLConnection) downpath.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

if(conn.getResponseCode()== 200){

int length = conn.getContentLength();//获取网络文件的长度

File file = new File(getFileName(path));//获取文件名

RandomAccessFile accessFile = newRandomAccessFile(file, "rwd");//生成本地文件

accessFile.setLength(length);

accessFile.close();

。。。

}

}

第二步:开启线程,计算每条线程下载数据量

//计算每条线程负责下载的数据量

int block = length %threadsize == 0 ? length / threadsize : length / threadsize +1;

for(int threadid = 0; threadid < threadsize ; threadid++){

newDownloadThread(threadid, downpath, block, file).start();

}

第三步:开始下载

部分代码:

publicvoid run() {

int startposition = threadid * block;//从网络文件的什么位置开始下载数据

int endposition = (threadid+1) * block - 1;//下载到网络文件的什么位置结束

//指示该线程要从网络文件的startposition位置开始下载,下载到endposition位置结束

//Range:bytes=startposition-endposition

try{

RandomAccessFileaccessFile = new RandomAccessFile(file, "rwd");

accessFile.seek(startposition);//移动指针到文件的某个位置

HttpURLConnectionconn = (HttpURLConnection) downpath.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

//分段下载的请求码不是200而是206,使用if(conn.getResponseCode() == 200){会出错

//System.out.println(conn.getResponseCode());

conn.setRequestProperty("Range","bytes="+ startposition+ "-"+ endposition);

InputStreaminStream = conn.getInputStream();

byte[]buffer = new byte[1024];

intlen = 0;

while((len = inStream.read(buffer)) != -1 ){

accessFile.write(buffer,0, len);

}

//}

accessFile.close();

inStream.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、付费专栏及课程。

余额充值