av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:2日期:2022-09-01 13:47:44

原理解析:

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

示例圖:

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

代碼如下

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 亚洲久久视频 | 国产黄a三级 | 69av在线 | 一区二区三区在线观看免费 | 88av在线| 一区二区三区成人 | 一级黄片毛片 | 天堂在线中文资源 | 色综合99| 成人毛片100免费观看 | 红桃av在线| 天堂中文字幕免费一区 | 亚洲国产中文字幕 | 国产免费福利 | 成年人视频网站 | cao在线| av在线免费网站 | 开心激情站| 欧美黄视频 | 日韩天堂在线 | 欧美一级黄色大片 | 久久久久久成人 | 九九九免费视频 | 婷婷久久综合 | 一级黄色免费视频 | 日本午夜精品 | 老女人毛片 | 免费av在线 | 男女瑟瑟视频 | 91日韩欧美| aa一级片| 成人午夜在线 | 久久久久国产精品夜夜夜夜夜 | 日韩黄网| 欧美精品二区三区四区免费看视频 | 亚洲理论片 | 国产欧美视频在线观看 | 香蕉网在线 | 一区二区视频在线 | 乳色吐息樱花 | 欧美成人精品激情在线观看 |