首页 > 代码库 > 多线程下载

多线程下载

多线程下载:1.发送请求,获取下载文件的长度2.通过RandomAccessFile file=new RandomAccessFile(file,"rwd")对象,创建一个于要下载文件同样大小的文件3.定义一个线程的数据,计算每条线程的下载量,long block=filesize%threadsize==0?filesize/threadsize:filesize/threadsize+14.定义一个内部类实现thread,作为下载的实现,把线程的id,和每条线程要下载的数量传递给这个类5.计算要下载的开始位置,和结束位置,start=id*block; end=(id+1)*block-1;6.设置分段请求,HttpGet get.setHread("Range","bytes="+start+"-"+end);7.分段请求的数据返回的状态码是206,之后获取通过RandomAccessFile对象的一个seek(start);方法,获取内容进行写入即可

public void download(View v) { new Thread(new Runnable() { public void run() { try { HttpClient client = new DefaultHttpClient(); HttpGet head = new HttpGet("http://10.0.2.2:8080/FoodService/a.mp4"); HttpResponse rsponse = client.execute(head); if (rsponse.getStatusLine().getStatusCode() == 200) { long length = rsponse.getEntity().getContentLength(); RandomAccessFile accessFile = new RandomAccessFile(new File(Environment.getExternalStorageDirectory(), "b.mp4"),"rwd"); accessFile.setLength(length); int size = 3; //根据线程的数量计算一个文件分为多少块 long block = length % size == 0 ? length / size: length / size + 1; for (int i = 0; i < size; i++) { new downLoadImage(i, block).start(); } } } catch (Exception e) { e.printStackTrace(); } } }).start();private class downLoadImage extends Thread { int threadid;//线程id long block;//下载的量 long start;//开始下载位置 long end;//结束的下载位置 public downLoadImage(int i, long block) { this.threadid = i; this.block = block; //计算每个线程的下载量 start=threadid*block; end=(threadid+1)*block-1; } public void run() { try { RandomAccessFile accessFile = new RandomAccessFile(new File(Environment.getExternalStorageDirectory(), "b.mp4"), "rwd"); accessFile.seek(start); HttpClient client=new DefaultHttpClient(); HttpGet request=new HttpGet("http://10.0.2.2:8080/FoodService/a.mp4"); request.setHeader("Range","bytes="+start+"-"+end); HttpResponse response = client.execute(request); if(response.getStatusLine().getStatusCode()==206){ InputStream inputStream = response.getEntity().getContent(); int len=0; byte[] buffer=new byte[1024]; while((len=inputStream.read(buffer))!=-1){ accessFile.write(buffer, 0, len); } inputStream.close(); Log.i("MainActivity", threadid+"线程"); } } catch (Exception e) { e.printStackTrace(); } } }