溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java多線程下載文件原理解析

發(fā)布時間:2020-08-27 03:39:34 來源:腳本之家 閱讀:189 作者:ITzhongzi 欄目:編程語言

原理解析:利用RandomAccessFile在本地創(chuàng)建一個隨機訪問文件,文件大小和服務(wù)器要下載的文件大小相同。根據(jù)線程的數(shù)量(假設(shè)有三個線程),服務(wù)器的文件三等分,并把我們在本地創(chuàng)建的文件同樣三等分,每個線程下載自己負責(zé)的部分,到相應(yīng)的位置即可。

示例圖:

java多線程下載文件原理解析

示例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; //每個現(xiàn)成下載的開始位置
          int endIndex = (i + 1) * blockSize - 1;// 每個線程的結(jié)束位置
          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) {

      }
    }
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI