歡迎您光臨本站 註冊首頁

Java多線程下載文件實現案例詳解

←手機掃碼閱讀     bom485332 @ 2020-06-10 , reply:0

原理解析:

利用RandomAccessFile在本地創建一個隨機訪問文件,文件大小和服務器要下載的文件大小相同。 根據線程的數量(假設有三個線程),服務器的文件三等分,並把我們在本地創建的文件同樣三等分,每個線程下載自己負責的部分,到相應的位置即可。

示例圖:

代碼如下

  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) {          }      }    }  }

 

                                                       

   


[bom485332 ] Java多線程下載文件實現案例詳解已經有238次圍觀

http://coctec.com/docs/java/show-post-237761.html