当前位置: 移动技术网 > IT编程>开发语言>Java > java多线程下载文件原理解析

java多线程下载文件原理解析

2019年07月19日  | 移动技术网IT编程  | 我要评论

原理解析:利用randomaccessfile在本地创建一个随机访问文件,文件大小和服务器要下载的文件大小相同。根据线程的数量(假设有三个线程),服务器的文件三等分,并把我们在本地创建的文件同样三等分,每个线程下载自己负责的部分,到相应的位置即可。

示例图:

示例demo

import java.io.inputstream;
import java.io.randomaccessfile;
import java.net.httpurlconnection;
import java.net.url;

public class mutildownload {
  private static string path = "http://192.168.80.85:8080/test.doc";
  private static final int threadcount = 3;

  public static void main(string[] args) {
    try {
      url url = new url(path);
      httpurlconnection conn = (httpurlconnection) url.openconnection();
      conn.setrequestmethod("get");
      conn.setconnecttimeout(5000);
      int responsecode = conn.getresponsecode();
      if (responsecode == 200) {
        int contentlength = conn.getcontentlength();
        system.out.println("length" + contentlength);

        randomaccessfile rafaccessfile = new randomaccessfile("test.doc", "rw");
        rafaccessfile.setlength(contentlength);

        int blocksize = contentlength / threadcount;
        for (int i = 0; i < threadcount; i++) {
          int startindex = i * blocksize; //每个现成下载的开始位置
          int endindex = (i + 1) * blocksize - 1;// 每个线程的结束位置
          if (i == threadcount - 1) {
            //最后一个线程
            endindex = contentlength - 1;
          }

          new downloadthread(startindex, endindex, i).start();
        }

      }
    } catch (exception e) {

    }
  }

  private static class downloadthread extends thread {
    private int startindex;
    private int endindex;
    private int threadid;

    public downloadthread(int startindex, int endindex, int threadid) {
      this.startindex = startindex;
      this.endindex = endindex;
      this.threadid = threadid;
    }

    @override
    public void run() {
      try {
        url url = new url(path);
        httpurlconnection conn = (httpurlconnection) url.openconnection();
        conn.setrequestmethod("get");
        conn.setconnecttimeout(5000);
        conn.setrequestproperty("range", "bytes=" + startindex + "-" + endindex); //固定写法,请求部分资源
        int responsecode = conn.getresponsecode(); // 206表示请求部分资源
        if (responsecode == 206) {
          randomaccessfile rafaccessfile = new randomaccessfile("test.doc", "rw");
          rafaccessfile.seek(startindex);
          inputstream is = conn.getinputstream();
          int len = -1;
          byte[] buffer = new byte[1024];
          while ((len = is.read(buffer)) != -1) {
            rafaccessfile.write(buffer, 0, len);
          }
          rafaccessfile.close();

          system.out.println("线程" + threadid + "下载完成");
        }
      } catch (exception e) {

      }
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网