多线程下载器

 

package cn.com.download;

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

public class MulThreadDownload {

 /**
  * @param args
  * @throws MalformedURLException
  */
 public static void main(String[] args) throws Exception {
  String path = "http://abdl.baofeng.com/actions/storm_715.exe";
  new MulThreadDownload().download(path,3);
 }
 /**
  * 下载文件
  * @param path 网络文件路径
  * @throws MalformedURLException
  */
 private void download(String path,int threadsize) throws Exception {
  URL url = new URL(path);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setConnectTimeout(5000);
  connection.setRequestMethod("GET");
  if(connection.getResponseCode()==200){//下载的connection.getResponseCode()==206
   //得到网络文件的长度
   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 threadid;
  private int block;
  private URL url;
  private File file;
  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);
    HttpURLConnection connection =(HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(5000);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Range","bytes="+start+"-"+end);
    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();
   }
  }
 }
 /**
  * 获得网络文件名称
  * @param path
  * @return
  */
 private String getFilename(String path) {
  return path.substring(path.lastIndexOf("/")+1);
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值