java多线程下载

来源:互联网 发布:知乎电脑下载 编辑:程序博客网 时间:2024/05/12 05:41

public class ThreahDownload {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws Exception {

  String path = new String(http://192.168.1.122/haha/GEM.mp3);          //需要下载的资源为主,本地tomcat
  new ThreahDownload().download(path, 3);                            //将需要下载资源的为主,需要开启的线程数作为参数开启线程下载
 }

 /**
  * 通过传入的url进行文件的下载
  *
  * @param string
  * @throws IOException
  */
 private void download(String path, int threadsize) throws Exception {

  URL url = new URL(path);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setConnectTimeout(5000);
  conn.setRequestMethod("GET");
  if (conn.getResponseCode() == 200) {
   int Length = conn.getContentLength();
   File file = new File(getFileName(path)); //  用getFileName()方法得到文件名称并本地创建一个文件
   RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
   accessFile.setLength(Length); // 设置本地创建一个文件长度和网络文件长度相等
   accessFile.close();

   int block = Length % threadsize == 0 ? Length / threadsize : Length                     //block为每一段线程段需要下载的长度
     / threadsize + 1;
   for (int threadid = 0; threadid < threadsize; threadid++) {                              //根据线程数开启线程
    new DownloadThread(threadid, block, url, file).start();                               //参数(线程id,下载大小,资源位置,保存位置)
   }

  } else {
   System.out.println("文件下载失败!");
  }
 }

 /**
  * 获得文件名称
  *
  * @param path
  * @return
  */
 private String getFileName(String path) {
  // TODO Auto-generated method stub
  return path.substring(path.lastIndexOf("/") + 1);
 }

 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) {
   // TODO Auto-generated constructor stub
   this.block = block;
   this.threadid = threadid;
   this.file = file;
   this.url = url;
  }

  @Override
  public void run() {
   // TODO Auto-generated method stub

   int start = threadid * block;                            //线程开始下载位置
   int end = (threadid + 1) * block - 1;               //线程结束位置
   try {
    RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
    accessFile.seek(start);
    HttpURLConnection conn = (HttpURLConnection) url
      .openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
    if (conn.getResponseCode() == 206) {                                                   //多线程连接成功码为206
     InputStream inStream = conn.getInputStream();
     byte[] buffer = new byte[1024];
     int len = 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();
   }

  }
 }
}

原创粉丝点击